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
1497E2
1497
E2
ru
E2. Бесквадратное разбиение (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Бесквадратное разбиение (сложная версия)</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">Это сложная версия задачи. Единственное отличие  — в этой версии задачи $$$0 \leq k \leq 20$$$.</span></p><p>Дан массив $$$a_1, a_2, \ldots, a_n$$$ из $$$n$$$ положительных целых чисел. Необходимо разбить его на наименьшее количество непрерывных отрезков так, чтобы ни на каком отрезке не было двух чисел (на разных позициях), произведение которых является полным квадратом.</p><p>При этом до разбиения разрешается сделать не более $$$k$$$ раз следующую операцию: выбрать любое число в массиве и заменить его значение на произвольное целое положительное число.</p><p>Какое наименьшее количество непрерывных отрезков нужно использовать, если сделать изменения оптимально?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ $$$(1 \le t \le 1000)$$$  — количество наборов входных данных.</p><p>Первая строка описания каждого набора входных данных содержит два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \leq k \leq 20$$$).</p><p>Вторая строка описания каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^7$$$).</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><div class="test-example-line test-example-line-even test-example-line-0">3</div><div class="test-example-line test-example-line-odd test-example-line-1">5 2</div><div class="test-example-line test-example-line-odd test-example-line-1">18 6 2 4 1</div><div class="test-example-line test-example-line-even test-example-line-2">11 4</div><div class="test-example-line test-example-line-even test-example-line-2">6 2 2 8 9 1 3 6 3 9 7</div><div class="test-example-line test-example-line-odd test-example-line-3">1 0</div><div class="test-example-line test-example-line-odd test-example-line-3">1</div></pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно сначала изменить массив следующим образом: $$$[\underline{3}, 6, 2, 4, \underline{5}]$$$ (изменённые числа подчёркнуты). После этого его не нужно разделять, поэтому ответ $$$1$$$.</p><p>Во втором наборе входных данных можно сначала изменить массив следующим образом: $$$[6, 2, \underline{3}, 8, 9, \underline{5}, 3, 6, \underline{10}, \underline{11}, 7]$$$. После этого такое разбиение будет оптимальным: </p><ul> <li> $$$[6, 2, 3]$$$ </li><li> $$$[8, 9, 5, 3, 6, 10, 11, 7]$$$ </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="c2fb057af2947005cb2dea572f6e93ea"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - E2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="2eb8610378b36d3c2c11deb0fcade0d29efe220e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c2fb057af2947005cb2dea572f6e93ea'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1497%2Fproblem%2FE2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='c2fb057af2947005cb2dea572f6e93ea'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1497">Codeforces Round 708 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c2fb057af2947005cb2dea572f6e93ea'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1497/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='c2fb057af2947005cb2dea572f6e93ea'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="925010"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c2fb057af2947005cb2dea572f6e93ea'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="925010"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88680" title="Codeforces Round #708" target="_blank">Codeforces Round #708</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13291:13292" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88677" title="Codeforces Round #708 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13304:13305" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1497">Задачи</a></li> <li><a href="/contest/1497/submit">Отослать</a></li> <li><a href="/contest/1497/my">Мои посылки</a></li> <li><a href="/contest/1497/status">Статус</a></li> <li><a href="/contest/1497/hacks">Взломы</a></li> <li><a href="/contest/1497/room/1">Комната</a></li> <li><a href="/contest/1497/standings">Положение</a></li> <li><a href="/contest/1497/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="E2" data-uuid="ps_bccdd4191baf6dc1211aef0ce230b0a14ec79e7b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E2. Бесквадратное разбиение (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>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">Это сложная версия задачи. Единственное отличие  — в этой версии задачи $$$0 \leq k \leq 20$$$.</span></p><p>Дан массив $$$a_1, a_2, \ldots, a_n$$$ из $$$n$$$ положительных целых чисел. Необходимо разбить его на наименьшее количество непрерывных отрезков так, чтобы ни на каком отрезке не было двух чисел (на разных позициях), произведение которых является полным квадратом.</p><p>При этом до разбиения разрешается сделать не более $$$k$$$ раз следующую операцию: выбрать любое число в массиве и заменить его значение на произвольное целое положительное число.</p><p>Какое наименьшее количество непрерывных отрезков нужно использовать, если сделать изменения оптимально?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ $$$(1 \le t \le 1000)$$$  — количество наборов входных данных.</p><p>Первая строка описания каждого набора входных данных содержит два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \leq k \leq 20$$$).</p><p>Вторая строка описания каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^7$$$).</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><div class="test-example-line test-example-line-even test-example-line-0">3</div><div class="test-example-line test-example-line-odd test-example-line-1">5 2</div><div class="test-example-line test-example-line-odd test-example-line-1">18 6 2 4 1</div><div class="test-example-line test-example-line-even test-example-line-2">11 4</div><div class="test-example-line test-example-line-even test-example-line-2">6 2 2 8 9 1 3 6 3 9 7</div><div class="test-example-line test-example-line-odd test-example-line-3">1 0</div><div class="test-example-line test-example-line-odd test-example-line-3">1</div></pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно сначала изменить массив следующим образом: $$$[\underline{3}, 6, 2, 4, \underline{5}]$$$ (изменённые числа подчёркнуты). После этого его не нужно разделять, поэтому ответ $$$1$$$.</p><p>Во втором наборе входных данных можно сначала изменить массив следующим образом: $$$[6, 2, \underline{3}, 8, 9, \underline{5}, 3, 6, \underline{10}, \underline{11}, 7]$$$. После этого такое разбиение будет оптимальным: </p><ul> <li> $$$[6, 2, 3]$$$ </li><li> $$$[8, 9, 5, 3, 6, 10, 11, 7]$$$ </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:06</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bd769e7a7b7f',t:'MTY5NjY2Njk4Ni4wODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\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", "\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", "\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", "*2500"]
1498A
1498
A
ru
A. GCD Sum
<div class="problem-statement"><div class="header"><div class="title">A. GCD Sum</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>$$$\text{$$$gcdSum$$$}$$$ положительного целого числа — это $$$gcd$$$ этого числа и суммы его цифр. Формально, $$$\text{$$$gcdSum$$$}(x) = gcd(x, \text{ сумма цифр } x)$$$ для положительного целого $$$x$$$. $$$gcd(a, b)$$$ обозначает наибольший общий делитель $$$a$$$ и $$$b$$$ — наибольшее целое число $$$d$$$, такое, что оба числа $$$a$$$ и $$$b$$$ делятся на $$$d$$$.</p><p>Например: $$$\text{$$$gcdSum$$$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$$$.</p><p>Вам дано целое число $$$n$$$. Найдите наименьшее целое число $$$x \ge n$$$, для которого $$$\text{$$$gcdSum$$$}(x) &gt; 1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ $$$(1 \le t \le 10^4)$$$ — количество наборов входных данных. </p><p>Затем следуют $$$t$$$ строк, каждая из которых содержит одно целое число $$$n$$$ $$$(1 \le n \le 10^{18})$$$.</p><p>Все наборы входных данных в одном тесте различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, $$$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> 3 11 31 75 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 33 75 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение трех наборов входных данных из примера:</p><p><span class="tex-font-style-bf">Набор 1:</span> $$$n = 11$$$: </p><p>$$$\text{$$$gcdSum$$$}(11) = gcd(11, 1 + 1) = gcd(11,\ 2) = 1$$$.</p><p>$$$\text{$$$gcdSum$$$}(12) = gcd(12, 1 + 2) = gcd(12,\ 3) = 3$$$.</p><p>Значит, минимальное целое число $$$\ge 11$$$, для которого $$$gcdSum$$$ $$$&gt; 1$$$ — это $$$12$$$.</p><p><span class="tex-font-style-bf">Набор 2:</span> $$$n = 31$$$: </p><p>$$$\text{$$$gcdSum$$$}(31) = gcd(31, 3 + 1) = gcd(31,\ 4) = 1$$$.</p><p>$$$\text{$$$gcdSum$$$}(32) = gcd(32, 3 + 2) = gcd(32,\ 5) = 1$$$.</p><p>$$$\text{$$$gcdSum$$$}(33) = gcd(33, 3 + 3) = gcd(33,\ 6) = 3$$$.</p><p>Значит, минимальное целое число $$$\ge 31$$$, для которого $$$gcdSum$$$ $$$&gt; 1$$$ — это $$$33$$$.</p><p><span class="tex-font-style-bf">Набор 3:</span> $$$\ n = 75$$$: </p><p>$$$\text{$$$gcdSum$$$}(75) = gcd(75, 7 + 5) = gcd(75,\ 12) = 3$$$.</p><p>$$$\text{$$$gcdSum$$$}$$$ числа $$$75$$$ уже $$$&gt; 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="2bfce75fd47a5b5cb052303c3a8f2e55"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="8c78c7c6424e0dbb287a71c86cc81212c11d8de4"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2bfce75fd47a5b5cb052303c3a8f2e55'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1498%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='2bfce75fd47a5b5cb052303c3a8f2e55'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1498">CodeCraft-21 and Codeforces Round 711 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2bfce75fd47a5b5cb052303c3a8f2e55'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1498/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='2bfce75fd47a5b5cb052303c3a8f2e55'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="939722"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2bfce75fd47a5b5cb052303c3a8f2e55'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="939722"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89069" title="CodeCraft-21 and Codeforces Round #711 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13386" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89137" title="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13409" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1498">Задачи</a></li> <li><a href="/contest/1498/submit">Отослать</a></li> <li><a href="/contest/1498/my">Мои посылки</a></li> <li><a href="/contest/1498/status">Статус</a></li> <li><a href="/contest/1498/hacks">Взломы</a></li> <li><a href="/contest/1498/room/1">Комната</a></li> <li><a href="/contest/1498/standings">Положение</a></li> <li><a href="/contest/1498/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_004649be6706571038e41735b733c6822d4cb778"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. GCD Sum</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>$$$\text{$$$gcdSum$$$}$$$ положительного целого числа — это $$$gcd$$$ этого числа и суммы его цифр. Формально, $$$\text{$$$gcdSum$$$}(x) = gcd(x, \text{ сумма цифр } x)$$$ для положительного целого $$$x$$$. $$$gcd(a, b)$$$ обозначает наибольший общий делитель $$$a$$$ и $$$b$$$ — наибольшее целое число $$$d$$$, такое, что оба числа $$$a$$$ и $$$b$$$ делятся на $$$d$$$.</p><p>Например: $$$\text{$$$gcdSum$$$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$$$.</p><p>Вам дано целое число $$$n$$$. Найдите наименьшее целое число $$$x \ge n$$$, для которого $$$\text{$$$gcdSum$$$}(x) &gt; 1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ $$$(1 \le t \le 10^4)$$$ — количество наборов входных данных. </p><p>Затем следуют $$$t$$$ строк, каждая из которых содержит одно целое число $$$n$$$ $$$(1 \le n \le 10^{18})$$$.</p><p>Все наборы входных данных в одном тесте различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, $$$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> 3 11 31 75 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 33 75 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение трех наборов входных данных из примера:</p><p><span class="tex-font-style-bf">Набор 1:</span> $$$n = 11$$$: </p><p>$$$\text{$$$gcdSum$$$}(11) = gcd(11, 1 + 1) = gcd(11,\ 2) = 1$$$.</p><p>$$$\text{$$$gcdSum$$$}(12) = gcd(12, 1 + 2) = gcd(12,\ 3) = 3$$$.</p><p>Значит, минимальное целое число $$$\ge 11$$$, для которого $$$gcdSum$$$ $$$&gt; 1$$$ — это $$$12$$$.</p><p><span class="tex-font-style-bf">Набор 2:</span> $$$n = 31$$$: </p><p>$$$\text{$$$gcdSum$$$}(31) = gcd(31, 3 + 1) = gcd(31,\ 4) = 1$$$.</p><p>$$$\text{$$$gcdSum$$$}(32) = gcd(32, 3 + 2) = gcd(32,\ 5) = 1$$$.</p><p>$$$\text{$$$gcdSum$$$}(33) = gcd(33, 3 + 3) = gcd(33,\ 6) = 3$$$.</p><p>Значит, минимальное целое число $$$\ge 31$$$, для которого $$$gcdSum$$$ $$$&gt; 1$$$ — это $$$33$$$.</p><p><span class="tex-font-style-bf">Набор 3:</span> $$$\ n = 75$$$: </p><p>$$$\text{$$$gcdSum$$$}(75) = gcd(75, 7 + 5) = gcd(75,\ 12) = 3$$$.</p><p>$$$\text{$$$gcdSum$$$}$$$ числа $$$75$$$ уже $$$&gt; 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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:17</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bd7edd881687',t:'MTY5NjY2Njk5Ny40MDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*800"]
1498B
1498
B
ru
B. Коробка
<div class="problem-statement"><div class="header"><div class="title">B. Коробка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть $$$n$$$ прямоугольников, каждый имеет высоту $$$1$$$. Ширина каждого прямоугольника — степень числа $$$2$$$ (т. е. ее можно представить как $$$2^x$$$ для некоторого неотрицательного целого $$$x$$$). </p><p>У вас также есть двумерная коробка ширины $$$W$$$. Обратите внимание, что $$$W$$$ может быть степенью числа $$$2$$$, а может и не быть. Точно известно, что $$$W$$$ не меньше ширины наибольшего прямоугольника.</p><p>Вы должны выбрать высоту этой коробки так, чтобы в нее можно было поместить все прямоугольники (при этом высоту необходимо минимизировать). Разрешается укладывать прямоугольники так, чтобы они не занимали все пространство коробки.</p><p>Прямоугольники нельзя вращать, кроме того, они не должны пересекаться после укладки (то есть для каждой пары прямоугольников, уложенных в коробку, их площадь пересечения должна быть нулевой).</p><p>Посмотрите пояснение для того, чтобы увидеть визуализацию условия задачи.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 5 \cdot 10^3$$$) — количество наборов входных данных. Каждый набор входных данных состоит из двух строк.</p><p>Для каждого набора:</p><ul><li> первая строка содержит два целых числа $$$n$$$ ($$$1 \le n \le 10^5$$$) и $$$W$$$ ($$$1 \le W \le 10^9$$$);</li><li> вторая строка содержит $$$n$$$ целых чисел $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^6$$$), где $$$w_i$$$ — ширина $$$i$$$-го прямоугольника. Каждое число $$$w_i$$$ является степенью числа $$$2$$$;</li><li> дополнительное ограничение: $$$\max\limits_{i=1}^{n} w_i \le W$$$. </li></ul><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел. $$$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 5 16 1 2 8 4 8 6 10 2 8 8 2 2 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор входных данных в примере разобран на следующей картинке:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/79e4c534eff8e73651beb3b3cc7a3a145a7ffb19.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>На этой картинке число внутри каждого прямоугольника — это его ширина. Ширина коробки равна $$$16$$$ (см. обозначения в нижней части картинки). Минимальная высота коробки равна $$$2$$$ (см. обозначения в левой части картинки).</p><p>Во втором наборе входных данных можно расположить на каждом уровне по одному прямоугольнику ширины 8 и ширины 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="97bc4ccece47dc8a16a6194048a37a41"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="8c78c7c6424e0dbb287a71c86cc81212c11d8de4"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='97bc4ccece47dc8a16a6194048a37a41'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1498%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='97bc4ccece47dc8a16a6194048a37a41'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1498">CodeCraft-21 and Codeforces Round 711 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='97bc4ccece47dc8a16a6194048a37a41'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1498/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='97bc4ccece47dc8a16a6194048a37a41'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="939723"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='97bc4ccece47dc8a16a6194048a37a41'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="939723"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89069" title="CodeCraft-21 and Codeforces Round #711 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13386" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89137" title="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13409" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1498">Задачи</a></li> <li><a href="/contest/1498/submit">Отослать</a></li> <li><a href="/contest/1498/my">Мои посылки</a></li> <li><a href="/contest/1498/status">Статус</a></li> <li><a href="/contest/1498/hacks">Взломы</a></li> <li><a href="/contest/1498/room/1">Комната</a></li> <li><a href="/contest/1498/standings">Положение</a></li> <li><a href="/contest/1498/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d40e7be34a0a0aab8a463c09a218f90b3593c3a6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Коробка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть $$$n$$$ прямоугольников, каждый имеет высоту $$$1$$$. Ширина каждого прямоугольника — степень числа $$$2$$$ (т. е. ее можно представить как $$$2^x$$$ для некоторого неотрицательного целого $$$x$$$). </p><p>У вас также есть двумерная коробка ширины $$$W$$$. Обратите внимание, что $$$W$$$ может быть степенью числа $$$2$$$, а может и не быть. Точно известно, что $$$W$$$ не меньше ширины наибольшего прямоугольника.</p><p>Вы должны выбрать высоту этой коробки так, чтобы в нее можно было поместить все прямоугольники (при этом высоту необходимо минимизировать). Разрешается укладывать прямоугольники так, чтобы они не занимали все пространство коробки.</p><p>Прямоугольники нельзя вращать, кроме того, они не должны пересекаться после укладки (то есть для каждой пары прямоугольников, уложенных в коробку, их площадь пересечения должна быть нулевой).</p><p>Посмотрите пояснение для того, чтобы увидеть визуализацию условия задачи.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 5 \cdot 10^3$$$) — количество наборов входных данных. Каждый набор входных данных состоит из двух строк.</p><p>Для каждого набора:</p><ul><li> первая строка содержит два целых числа $$$n$$$ ($$$1 \le n \le 10^5$$$) и $$$W$$$ ($$$1 \le W \le 10^9$$$);</li><li> вторая строка содержит $$$n$$$ целых чисел $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^6$$$), где $$$w_i$$$ — ширина $$$i$$$-го прямоугольника. Каждое число $$$w_i$$$ является степенью числа $$$2$$$;</li><li> дополнительное ограничение: $$$\max\limits_{i=1}^{n} w_i \le W$$$. </li></ul><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел. $$$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 5 16 1 2 8 4 8 6 10 2 8 8 2 2 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор входных данных в примере разобран на следующей картинке:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/79e4c534eff8e73651beb3b3cc7a3a145a7ffb19.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>На этой картинке число внутри каждого прямоугольника — это его ширина. Ширина коробки равна $$$16$$$ (см. обозначения в нижней части картинки). Минимальная высота коробки равна $$$2$$$ (см. обозначения в левой части картинки).</p><p>Во втором наборе входных данных можно расположить на каждом уровне по одному прямоугольнику ширины 8 и ширины 2, так потребуется всего три уровня (и высота коробки будет равна 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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:18</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bdc56af07b1b',t:'MTY5NjY2Njk5OC45NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1300"]
1498C
1498
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>Гауранг вырос в таинственной вселенной. Перед ним стоят $$$n$$$ 2D плоскостей одна за другой. Он пускает частицу с периодом распада $$$k$$$ в направлении плоскостей.</p><p>Частица может пройти через плоскость напрямую, однако, каждая плоскость создает идентичную копию этой частицы, направленную в противоположном направлении с периодом распада равным $$$k-1$$$. Если период распада частицы равен $$$1$$$, то она НЕ создаст копию.</p><p>Например, если есть две плоскости, и выпущена частица с периодом распада $$$3$$$ (направлена вправо), то происходит следующий процесс: (здесь $$$D(x)$$$ означает одну частицу с периодом распада $$$x$$$)</p><ol><li> первая плоскость создает $$$D(2)$$$ влево и пропускает $$$D(3)$$$ дальше вправо; </li><li> вторая плоскость создает $$$D(2)$$$ влево и пропускает $$$D(3)$$$ дальше вправо; </li><li> первая плоскость пропускает $$$D(2)$$$ дальше влево и создает $$$D(1)$$$ вправо; </li><li> вторая плоскость пропускает $$$D(1)$$$ дальше вправо ($$$D(1)$$$ не может создавать копии). </li></ol><p>В конце мультимножество $$$S$$$ всех частиц — это $$$\{D(3), D(2), D(2), D(1)\}$$$. (Смотрите примеры для визуального отображения этого теста.)</p><p>Гауранг не справляется со сложностью этого процесса, когда количество плоскостей слишком велико. Помогите Гаурангу узнать размер мультимножества $$$S$$$ по заданным $$$n$$$ и $$$k$$$.</p><p>Так как размер мультимножества может быть очень большим, выведите его по модулю $$$10^9+7$$$.</p><p>Обратите внимание, что частицы могут перемещаться между плоскостями, не сталкиваясь друг с другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Затем следуют $$$t$$$ строк, в каждой записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 1000$$$).</p><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$1000$$$. Сумма $$$k$$$ по всем наборам входных данных не превосходит $$$1000$$$. Все наборы входных данных в одном тесте различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел. $$$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> 4 2 3 2 2 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 1 500 500 250 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 257950823 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Здесь следует объяснение первого примера, состоящего из четырех наборов входных данных.</p><p><span class="tex-font-style-bf">Набор входных данных 1</span>: ($$$n = 2$$$, $$$k = 3$$$) уже объяснен в условии задачи.</p><p>На картинке ниже изображена симуляция. Каждая цветная прямая показывает путь одной из частиц. Как можно видеть, всего есть четыре различных частицы в мультимножестве. Обратите внимание, что вертикальные промежутки между отраженными частицами введены только для визуальной ясности (как ранее описывалось, частицы не сталкиваются друг с другом)</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7d007685aedd02b4ab90f70bf4cbd9b48bad1524.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-bf">Набор входных данных 2</span>: ($$$n = 2$$$, $$$k = 2$$$) выглядит так:</p><ol><li> первая плоскость создает $$$D(1)$$$ влево и пропускает $$$D(2)$$$ дальше вправо; </li><li> вторая плоскость создает $$$D(1)$$$ влево и пропускает $$$D(2)$$$ дальше вправо; </li><li> первая плоскость пропускает $$$D(1)$$$ дальше влево ($$$D(1)$$$ не может создавать копии).</li></ol><p>Итоговый размер мультимножества $$$\{D(1), D(1), D(2)\}$$$ равен трем.</p><p><span class="tex-font-style-bf">Набор входных данных 3</span>: ($$$n = 3$$$, $$$k = 1$$$) — здесь есть три плоскости, но период распада всего один. Поэтому новые копии не создаются, когда одна частица пролетает через плоскости. Поэтому ответ один.</p><p><span class="tex-font-style-bf">Набор входных данных 4</span>: ($$$n = 1$$$, $$$k = 3$$$) — здесь только одна плоскость. Частица создает новую копию влево. Мультимножество $$$\{D(2), D(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="b222d630927675f552d9d91ea3e5fa6c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="8c78c7c6424e0dbb287a71c86cc81212c11d8de4"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b222d630927675f552d9d91ea3e5fa6c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1498%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='b222d630927675f552d9d91ea3e5fa6c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1498">CodeCraft-21 and Codeforces Round 711 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b222d630927675f552d9d91ea3e5fa6c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1498/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='b222d630927675f552d9d91ea3e5fa6c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="939724"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b222d630927675f552d9d91ea3e5fa6c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="939724"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89069" title="CodeCraft-21 and Codeforces Round #711 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13386" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89137" title="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13409" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1498">Задачи</a></li> <li><a href="/contest/1498/submit">Отослать</a></li> <li><a href="/contest/1498/my">Мои посылки</a></li> <li><a href="/contest/1498/status">Статус</a></li> <li><a href="/contest/1498/hacks">Взломы</a></li> <li><a href="/contest/1498/room/1">Комната</a></li> <li><a href="/contest/1498/standings">Положение</a></li> <li><a href="/contest/1498/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f9b7b9eab00f4e3af80def46635b3e3f061b7033"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Гауранг вырос в таинственной вселенной. Перед ним стоят $$$n$$$ 2D плоскостей одна за другой. Он пускает частицу с периодом распада $$$k$$$ в направлении плоскостей.</p><p>Частица может пройти через плоскость напрямую, однако, каждая плоскость создает идентичную копию этой частицы, направленную в противоположном направлении с периодом распада равным $$$k-1$$$. Если период распада частицы равен $$$1$$$, то она НЕ создаст копию.</p><p>Например, если есть две плоскости, и выпущена частица с периодом распада $$$3$$$ (направлена вправо), то происходит следующий процесс: (здесь $$$D(x)$$$ означает одну частицу с периодом распада $$$x$$$)</p><ol><li> первая плоскость создает $$$D(2)$$$ влево и пропускает $$$D(3)$$$ дальше вправо; </li><li> вторая плоскость создает $$$D(2)$$$ влево и пропускает $$$D(3)$$$ дальше вправо; </li><li> первая плоскость пропускает $$$D(2)$$$ дальше влево и создает $$$D(1)$$$ вправо; </li><li> вторая плоскость пропускает $$$D(1)$$$ дальше вправо ($$$D(1)$$$ не может создавать копии). </li></ol><p>В конце мультимножество $$$S$$$ всех частиц — это $$$\{D(3), D(2), D(2), D(1)\}$$$. (Смотрите примеры для визуального отображения этого теста.)</p><p>Гауранг не справляется со сложностью этого процесса, когда количество плоскостей слишком велико. Помогите Гаурангу узнать размер мультимножества $$$S$$$ по заданным $$$n$$$ и $$$k$$$.</p><p>Так как размер мультимножества может быть очень большим, выведите его по модулю $$$10^9+7$$$.</p><p>Обратите внимание, что частицы могут перемещаться между плоскостями, не сталкиваясь друг с другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Затем следуют $$$t$$$ строк, в каждой записаны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 1000$$$).</p><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$1000$$$. Сумма $$$k$$$ по всем наборам входных данных не превосходит $$$1000$$$. Все наборы входных данных в одном тесте различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел. $$$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> 4 2 3 2 2 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 1 500 500 250 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 257950823 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Здесь следует объяснение первого примера, состоящего из четырех наборов входных данных.</p><p><span class="tex-font-style-bf">Набор входных данных 1</span>: ($$$n = 2$$$, $$$k = 3$$$) уже объяснен в условии задачи.</p><p>На картинке ниже изображена симуляция. Каждая цветная прямая показывает путь одной из частиц. Как можно видеть, всего есть четыре различных частицы в мультимножестве. Обратите внимание, что вертикальные промежутки между отраженными частицами введены только для визуальной ясности (как ранее описывалось, частицы не сталкиваются друг с другом)</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7d007685aedd02b4ab90f70bf4cbd9b48bad1524.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-bf">Набор входных данных 2</span>: ($$$n = 2$$$, $$$k = 2$$$) выглядит так:</p><ol><li> первая плоскость создает $$$D(1)$$$ влево и пропускает $$$D(2)$$$ дальше вправо; </li><li> вторая плоскость создает $$$D(1)$$$ влево и пропускает $$$D(2)$$$ дальше вправо; </li><li> первая плоскость пропускает $$$D(1)$$$ дальше влево ($$$D(1)$$$ не может создавать копии).</li></ol><p>Итоговый размер мультимножества $$$\{D(1), D(1), D(2)\}$$$ равен трем.</p><p><span class="tex-font-style-bf">Набор входных данных 3</span>: ($$$n = 3$$$, $$$k = 1$$$) — здесь есть три плоскости, но период распада всего один. Поэтому новые копии не создаются, когда одна частица пролетает через плоскости. Поэтому ответ один.</p><p><span class="tex-font-style-bf">Набор входных данных 4</span>: ($$$n = 1$$$, $$$k = 3$$$) — здесь только одна плоскость. Частица создает новую копию влево. Мультимножество $$$\{D(2), D(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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:20</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bdcf5dfb9d67',t:'MTY5NjY2NzAwMC41MTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"]
1498D
1498
D
ru
D. Бананы в микроволновке
<div class="problem-statement"><div class="header"><div class="title">D. Бананы в микроволновке</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть сломанная микроволновка, в которую вы хотите положить несколько бананов. У вас есть $$$n$$$ моментов времени, пока микроволновка не сломается окончательно. В каждый момент времени она показывает новую операцию.</p><p>Пусть $$$k$$$ будет равно текущему количеству бананов в микроволновке. Изначально $$$k = 0$$$. В $$$i$$$-й операции на вход подаются три параметра $$$t_i$$$, $$$x_i$$$, $$$y_i$$$. В зависимости от значения $$$t_i$$$ необходимо сделать одно из следующий действий:</p><p><span class="tex-font-style-bf">Тип 1</span>: ($$$t_i=1$$$, $$$x_i$$$, $$$y_i$$$) — выберите $$$a_i$$$ такое, что $$$0 \le a_i \le y_i$$$, и произведите следующую замену $$$a_i$$$ раз: $$$k:=\lceil (k + x_i) \rceil$$$.</p><p><span class="tex-font-style-bf">Тип 2</span>: ($$$t_i=2$$$, $$$x_i$$$, $$$y_i$$$) — выберите $$$a_i$$$ такое, что $$$0 \le a_i \le y_i$$$, и произведите следующую замену $$$a_i$$$ раз: $$$k:=\lceil (k \cdot x_i) \rceil$$$.</p><p>Обратите внимание, что <span class="tex-font-style-bf">$$$x_i$$$ может быть дробным значением</span>. Смотрите формат входных данных для пояснения. Также $$$\lceil x \rceil$$$ — это наименьшее целое число $$$\ge x$$$.</p><p>В $$$i$$$-й момент времени необходимо произвести $$$i$$$-ю операцию ровно один раз.</p><p>Для каждого $$$j$$$ такого, что $$$1 \le j \le m$$$, выведите самый ранний момент времени такой, что вы можете получить <span class="tex-font-style-bf">ровно</span> $$$j$$$ бананов. Если нельзя получить <span class="tex-font-style-bf">ровно</span> $$$j$$$ бананов, то выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ $$$(1 \le n \le 200)$$$ и $$$m$$$ $$$(2 \le m \le 10^5)$$$.</p><p>Затем следуют $$$n$$$ строк, где $$$i$$$-я строка описывает операцию в $$$i$$$-й момент времени. Каждая строка содержит три целых числа $$$t_i$$$, $$$x'_i$$$ и $$$y_i$$$ ($$$1 \le t_i \le 2$$$, $$$1\le y_i\le m$$$).</p><p>Обратите внимание, что задается $$$x'_i$$$, которое равно $$$10^5 \cdot x_i$$$. Чтобы получить $$$x_i$$$, используйте формулу $$$x_i= \dfrac{x'_i} {10^5}$$$.</p><p>Для операций <span class="tex-font-style-bf">типа 1</span> $$$1 \le x'_i \le 10^5 \cdot m$$$, а для операций <span class="tex-font-style-bf">типа 2</span> $$$10^5 &lt; x'_i \le 10^5 \cdot m$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел, где $$$i$$$-е число равно самому раннему моменту времени, в который можно получить <span class="tex-font-style-bf">ровно</span> $$$i$$$ бананов (или $$$-1$$$, если это невозможно).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 20 1 300000 2 2 400000 2 1 1000000 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 20 1 399999 2 2 412345 2 1 1000001 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-bf">В первом примере</span> мы хотим показать, как получить $$$16$$$ бананов за три момента времени. Изначально $$$k=0$$$.</p><ul> <li> В момент времени 1 мы выбираем $$$a_1=2$$$, поэтому мы применяем обновление типа 1 — $$$k := \lceil(k+3)\rceil$$$ — два раза. Поэтому $$$k$$$ теперь 6. </li><li> В момент времени 2 мы выбираем $$$a_2=0$$$, поэтому $$$k$$$ не изменяется. </li><li> В момент времени 3 мы выбираем $$$a_3=1$$$, поэтому мы применяем обновление типа 1 $$$k:= \lceil(k+10)\rceil$$$ один раз. Поэтому $$$k$$$ теперь 16. </li></ul><p>Можно показать, что $$$k=16$$$ нельзя получить быстрее, чем за три момента времени, используя данные операции.</p><p><span class="tex-font-style-bf">Во втором примере</span> мы хотим показать, как получить $$$17$$$ бананов за два момента времени. Изначально $$$k=0$$$.</p><ul> <li> В момент времени 1 мы выбираем $$$a_1=1$$$, поэтому мы применяем обновление типа 1 — $$$k := \lceil(k+3.99999)\rceil$$$ — один раз. Поэтому $$$k$$$ теперь 4. </li><li> В момент времени 2 мы выбираем $$$a_2=1$$$, поэтому мы применяем обновление типа 2 — $$$k := \lceil(k\cdot 4.12345)\rceil$$$ — один раз. Поэтому $$$k$$$ теперь 17. </li></ul><p>Можно показать, что $$$k=17$$$ нельзя получить быстрее, чем за два момента времени, используя данные операции.</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="195d8e46d53666cd9b5c5a658cf2eec3"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="8c78c7c6424e0dbb287a71c86cc81212c11d8de4"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='195d8e46d53666cd9b5c5a658cf2eec3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1498%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='195d8e46d53666cd9b5c5a658cf2eec3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1498">CodeCraft-21 and Codeforces Round 711 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='195d8e46d53666cd9b5c5a658cf2eec3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1498/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='195d8e46d53666cd9b5c5a658cf2eec3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="939725"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='195d8e46d53666cd9b5c5a658cf2eec3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="939725"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89069" title="CodeCraft-21 and Codeforces Round #711 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13386" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89137" title="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13409" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1498">Задачи</a></li> <li><a href="/contest/1498/submit">Отослать</a></li> <li><a href="/contest/1498/my">Мои посылки</a></li> <li><a href="/contest/1498/status">Статус</a></li> <li><a href="/contest/1498/hacks">Взломы</a></li> <li><a href="/contest/1498/room/1">Комната</a></li> <li><a href="/contest/1498/standings">Положение</a></li> <li><a href="/contest/1498/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_03e566b6956923ae3f22a083c3fa0dd24abbf17b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Бананы в микроволновке</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть сломанная микроволновка, в которую вы хотите положить несколько бананов. У вас есть $$$n$$$ моментов времени, пока микроволновка не сломается окончательно. В каждый момент времени она показывает новую операцию.</p><p>Пусть $$$k$$$ будет равно текущему количеству бананов в микроволновке. Изначально $$$k = 0$$$. В $$$i$$$-й операции на вход подаются три параметра $$$t_i$$$, $$$x_i$$$, $$$y_i$$$. В зависимости от значения $$$t_i$$$ необходимо сделать одно из следующий действий:</p><p><span class="tex-font-style-bf">Тип 1</span>: ($$$t_i=1$$$, $$$x_i$$$, $$$y_i$$$) — выберите $$$a_i$$$ такое, что $$$0 \le a_i \le y_i$$$, и произведите следующую замену $$$a_i$$$ раз: $$$k:=\lceil (k + x_i) \rceil$$$.</p><p><span class="tex-font-style-bf">Тип 2</span>: ($$$t_i=2$$$, $$$x_i$$$, $$$y_i$$$) — выберите $$$a_i$$$ такое, что $$$0 \le a_i \le y_i$$$, и произведите следующую замену $$$a_i$$$ раз: $$$k:=\lceil (k \cdot x_i) \rceil$$$.</p><p>Обратите внимание, что <span class="tex-font-style-bf">$$$x_i$$$ может быть дробным значением</span>. Смотрите формат входных данных для пояснения. Также $$$\lceil x \rceil$$$ — это наименьшее целое число $$$\ge x$$$.</p><p>В $$$i$$$-й момент времени необходимо произвести $$$i$$$-ю операцию ровно один раз.</p><p>Для каждого $$$j$$$ такого, что $$$1 \le j \le m$$$, выведите самый ранний момент времени такой, что вы можете получить <span class="tex-font-style-bf">ровно</span> $$$j$$$ бананов. Если нельзя получить <span class="tex-font-style-bf">ровно</span> $$$j$$$ бананов, то выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ $$$(1 \le n \le 200)$$$ и $$$m$$$ $$$(2 \le m \le 10^5)$$$.</p><p>Затем следуют $$$n$$$ строк, где $$$i$$$-я строка описывает операцию в $$$i$$$-й момент времени. Каждая строка содержит три целых числа $$$t_i$$$, $$$x'_i$$$ и $$$y_i$$$ ($$$1 \le t_i \le 2$$$, $$$1\le y_i\le m$$$).</p><p>Обратите внимание, что задается $$$x'_i$$$, которое равно $$$10^5 \cdot x_i$$$. Чтобы получить $$$x_i$$$, используйте формулу $$$x_i= \dfrac{x'_i} {10^5}$$$.</p><p>Для операций <span class="tex-font-style-bf">типа 1</span> $$$1 \le x'_i \le 10^5 \cdot m$$$, а для операций <span class="tex-font-style-bf">типа 2</span> $$$10^5 &lt; x'_i \le 10^5 \cdot m$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел, где $$$i$$$-е число равно самому раннему моменту времени, в который можно получить <span class="tex-font-style-bf">ровно</span> $$$i$$$ бананов (или $$$-1$$$, если это невозможно).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 20 1 300000 2 2 400000 2 1 1000000 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 -1 1 -1 -1 1 -1 -1 -1 3 -1 2 3 -1 -1 3 -1 -1 -1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 20 1 399999 2 2 412345 2 1 1000001 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 -1 -1 1 -1 -1 -1 1 -1 -1 3 -1 -1 -1 3 -1 2 -1 3 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-bf">В первом примере</span> мы хотим показать, как получить $$$16$$$ бананов за три момента времени. Изначально $$$k=0$$$.</p><ul> <li> В момент времени 1 мы выбираем $$$a_1=2$$$, поэтому мы применяем обновление типа 1 — $$$k := \lceil(k+3)\rceil$$$ — два раза. Поэтому $$$k$$$ теперь 6. </li><li> В момент времени 2 мы выбираем $$$a_2=0$$$, поэтому $$$k$$$ не изменяется. </li><li> В момент времени 3 мы выбираем $$$a_3=1$$$, поэтому мы применяем обновление типа 1 $$$k:= \lceil(k+10)\rceil$$$ один раз. Поэтому $$$k$$$ теперь 16. </li></ul><p>Можно показать, что $$$k=16$$$ нельзя получить быстрее, чем за три момента времени, используя данные операции.</p><p><span class="tex-font-style-bf">Во втором примере</span> мы хотим показать, как получить $$$17$$$ бананов за два момента времени. Изначально $$$k=0$$$.</p><ul> <li> В момент времени 1 мы выбираем $$$a_1=1$$$, поэтому мы применяем обновление типа 1 — $$$k := \lceil(k+3.99999)\rceil$$$ — один раз. Поэтому $$$k$$$ теперь 4. </li><li> В момент времени 2 мы выбираем $$$a_2=1$$$, поэтому мы применяем обновление типа 2 — $$$k := \lceil(k\cdot 4.12345)\rceil$$$ — один раз. Поэтому $$$k$$$ теперь 17. </li></ul><p>Можно показать, что $$$k=17$$$ нельзя получить быстрее, чем за два момента времени, используя данные операции.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:21</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bdd8dc0a0069',t:'MTY5NjY2NzAwMS45NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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", "*2200"]
1498E
1498
E
ru
E. Два дома
<div class="problem-statement"><div class="header"><div class="title">E. Два дома</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача. Не забывайте о том, что ваша программа должна каждый раз после вывода запроса сбрасывать буфер вывода.</span> Для сброса буфера вывода можно использовать <span class="tex-font-style-tt">fflush(stdout)</span> в C++, <span class="tex-font-style-tt">system.out.flush()</span> в Java, <span class="tex-font-style-tt">stdout.flush()</span> в Python или <span class="tex-font-style-tt">flush(output)</span> в Pascal. Если вы используете другой язык программирования, посмотрите в его документации, как выполняется эта операция. Также рекомендуем вам прочесть руководство по интерактивным задачам: <a href="https://codeforces.com/blog/entry/45307">https://codeforces.com/blog/entry/45307</a>.</p><p>Диксит живет в городе, в котором $$$n$$$ домов. Между каждой парой домов <span class="tex-font-style-bf">есть ровно одна направленная дорога.</span> То есть для любой пары домов A и B есть либо дорога от дома A к дому B, либо дорога от B к A (но только одна из них). К $$$i$$$-му дому ведут $$$k_i$$$ дорог.</p><p>Два дома A и B являются взаимно достижимыми, если дом A достижим из дома B (существует путь от дома A к дому B по дорогам), и дом B достижим из дома A.</p><p>Диксит хочет купить в этом городе два дома, один для того, чтобы жить в нем, другой — для учебы. Естественно, он бы хотел, чтобы от каждого из этих домов можно было добраться до другого дома, то есть ему нужно найти пару взаимно достижимых домов. Если таких пар несколько, Диксит хочет максимизировать величину $$$|k_A - k_B|$$$, где $$$k_i$$$ — количество дорог, ведущих к дому $$$i$$$. Если существует более одной оптимальной пары, подойдет любая из них.</p><p>Так как Диксит занят подготовкой CodeCraft, он просит вас помочь ему найти два таких дома, или сообщить, что таких домов нет.</p><p>Во входных данных задачи вам <span class="tex-font-style-bf">не</span> задаются направления дорог. Вы знаете только количество дорог, идущих к каждому дому ($$$k_i$$$).</p><p>Вы можете задавать запросы следующих типов: вы выводите пару домов A и B, и жюри ответит, есть ли путь от дома A к дому B. В этой задаче <span class="tex-font-style-bf">нет никакого явного ограничения на количество запросов, которые вы можете задать</span>. Но <span class="tex-font-style-bf">нельзя задавать запросы после того, как жюри ответит «<span class="tex-font-style-tt">Yes</span>» на один из ваших запросов.</span> Кроме того, нельзя задавать один и тот же запрос дважды.</p><p>Как только вы зададите все необходимые запросы (или жюри ответит «<span class="tex-font-style-tt">Yes</span>» на один из них), ваша программа должна вывести ответ и завершиться.</p><p>Прочтите раздел «Протокол взаимодействия» для того, чтобы получить более подробную информацию о взаимодействии.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$3 \le n \le 500$$$) — количество домов в городе. Во второй строке заданы $$$n$$$ целых чисел $$$k_1, k_2, \dots, k_n$$$ ($$$0 \le k_i \le n - 1$$$), $$$i$$$-е из которых равно кол-ву дорог, идущих к $$$i$$$-му дому.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы задать запрос, выведите «<span class="tex-font-style-tt">? A B</span>» $$$(1 \leq A,B \leq N, A\neq B)$$$. Программа жюри ответит «<span class="tex-font-style-tt">Yes</span>», если есть путь от дома A к дому B, или «<span class="tex-font-style-tt">No</span>», если пути нет.</p><p>Чтобы дать ответ на задачу, выведите «<span class="tex-font-style-tt">! A B</span>», где A и B — номера двух различных домов, достижимых друг из друга, с максимально возможной величиной $$$|k_A - k_B|$$$. Если такой пары домов не существует, выведите «<span class="tex-font-style-tt">! 0 0</span>».</p><p>После вывода ответа ваша программа должна завершиться, иначе вы получите вердикт «Неправильный ответ».</p><p>Вы не можете задавать один и тот же запрос дважды. <span class="tex-font-style-bf">Нет никакого ограничения на количество запросов, но вы не можете задавать запросы после получения ответа «<span class="tex-font-style-tt">Yes</span>».</span> После этого ваша программа сразу должна вывести ответ на задачу («<span class="tex-font-style-tt">! A B</span>» или «<span class="tex-font-style-tt">! 0 0</span>») и завершиться.</p><p>Если вы зададите запрос в неправильном формате или зададите один и тот же запрос дважды, вы получите вердикт «Неправильный ответ».</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></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 1 Yes</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ! 1 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 0 3 No No No No No No</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нам задан город с тремя домами, в каждый из которых ведет по одной дороге. Решение участника задает запрос «<span class="tex-font-style-tt">? 1 2</span>», чтобы узнать, можно ли от дома $$$1$$$ добраться до дома $$$2$$$. Программа жюри отвечает «<span class="tex-font-style-tt">Yes</span>». После этого решение участника выводит ответ «<span class="tex-font-style-tt">! 1 2</span>» и завершается.</p><p>Во втором примере решение участника делает шесть различных запросов, убеждается в том, что пары домов, достижимых друг из друга, нет, и выводит «<span class="tex-font-style-tt">! 0 0</span>» в качестве ответа.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f3bef2d1655e51e56660eed559fa9086"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="8c78c7c6424e0dbb287a71c86cc81212c11d8de4"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f3bef2d1655e51e56660eed559fa9086'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1498%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='f3bef2d1655e51e56660eed559fa9086'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1498">CodeCraft-21 and Codeforces Round 711 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='f3bef2d1655e51e56660eed559fa9086'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1498/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='f3bef2d1655e51e56660eed559fa9086'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="939726"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f3bef2d1655e51e56660eed559fa9086'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="939726"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89069" title="CodeCraft-21 and Codeforces Round #711 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13386" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89137" title="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13409" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1498">Задачи</a></li> <li><a href="/contest/1498/submit">Отослать</a></li> <li><a href="/contest/1498/my">Мои посылки</a></li> <li><a href="/contest/1498/status">Статус</a></li> <li><a href="/contest/1498/hacks">Взломы</a></li> <li><a href="/contest/1498/room/1">Комната</a></li> <li><a href="/contest/1498/standings">Положение</a></li> <li><a href="/contest/1498/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2e5296b8f5c9d6ae8b860174609ec82ea32db1f1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Два дома</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача. Не забывайте о том, что ваша программа должна каждый раз после вывода запроса сбрасывать буфер вывода.</span> Для сброса буфера вывода можно использовать <span class="tex-font-style-tt">fflush(stdout)</span> в C++, <span class="tex-font-style-tt">system.out.flush()</span> в Java, <span class="tex-font-style-tt">stdout.flush()</span> в Python или <span class="tex-font-style-tt">flush(output)</span> в Pascal. Если вы используете другой язык программирования, посмотрите в его документации, как выполняется эта операция. Также рекомендуем вам прочесть руководство по интерактивным задачам: <a href="https://codeforces.com/blog/entry/45307">https://codeforces.com/blog/entry/45307</a>.</p><p>Диксит живет в городе, в котором $$$n$$$ домов. Между каждой парой домов <span class="tex-font-style-bf">есть ровно одна направленная дорога.</span> То есть для любой пары домов A и B есть либо дорога от дома A к дому B, либо дорога от B к A (но только одна из них). К $$$i$$$-му дому ведут $$$k_i$$$ дорог.</p><p>Два дома A и B являются взаимно достижимыми, если дом A достижим из дома B (существует путь от дома A к дому B по дорогам), и дом B достижим из дома A.</p><p>Диксит хочет купить в этом городе два дома, один для того, чтобы жить в нем, другой — для учебы. Естественно, он бы хотел, чтобы от каждого из этих домов можно было добраться до другого дома, то есть ему нужно найти пару взаимно достижимых домов. Если таких пар несколько, Диксит хочет максимизировать величину $$$|k_A - k_B|$$$, где $$$k_i$$$ — количество дорог, ведущих к дому $$$i$$$. Если существует более одной оптимальной пары, подойдет любая из них.</p><p>Так как Диксит занят подготовкой CodeCraft, он просит вас помочь ему найти два таких дома, или сообщить, что таких домов нет.</p><p>Во входных данных задачи вам <span class="tex-font-style-bf">не</span> задаются направления дорог. Вы знаете только количество дорог, идущих к каждому дому ($$$k_i$$$).</p><p>Вы можете задавать запросы следующих типов: вы выводите пару домов A и B, и жюри ответит, есть ли путь от дома A к дому B. В этой задаче <span class="tex-font-style-bf">нет никакого явного ограничения на количество запросов, которые вы можете задать</span>. Но <span class="tex-font-style-bf">нельзя задавать запросы после того, как жюри ответит «<span class="tex-font-style-tt">Yes</span>» на один из ваших запросов.</span> Кроме того, нельзя задавать один и тот же запрос дважды.</p><p>Как только вы зададите все необходимые запросы (или жюри ответит «<span class="tex-font-style-tt">Yes</span>» на один из них), ваша программа должна вывести ответ и завершиться.</p><p>Прочтите раздел «Протокол взаимодействия» для того, чтобы получить более подробную информацию о взаимодействии.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$3 \le n \le 500$$$) — количество домов в городе. Во второй строке заданы $$$n$$$ целых чисел $$$k_1, k_2, \dots, k_n$$$ ($$$0 \le k_i \le n - 1$$$), $$$i$$$-е из которых равно кол-ву дорог, идущих к $$$i$$$-му дому.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы задать запрос, выведите «<span class="tex-font-style-tt">? A B</span>» $$$(1 \leq A,B \leq N, A\neq B)$$$. Программа жюри ответит «<span class="tex-font-style-tt">Yes</span>», если есть путь от дома A к дому B, или «<span class="tex-font-style-tt">No</span>», если пути нет.</p><p>Чтобы дать ответ на задачу, выведите «<span class="tex-font-style-tt">! A B</span>», где A и B — номера двух различных домов, достижимых друг из друга, с максимально возможной величиной $$$|k_A - k_B|$$$. Если такой пары домов не существует, выведите «<span class="tex-font-style-tt">! 0 0</span>».</p><p>После вывода ответа ваша программа должна завершиться, иначе вы получите вердикт «Неправильный ответ».</p><p>Вы не можете задавать один и тот же запрос дважды. <span class="tex-font-style-bf">Нет никакого ограничения на количество запросов, но вы не можете задавать запросы после получения ответа «<span class="tex-font-style-tt">Yes</span>».</span> После этого ваша программа сразу должна вывести ответ на задачу («<span class="tex-font-style-tt">! A B</span>» или «<span class="tex-font-style-tt">! 0 0</span>») и завершиться.</p><p>Если вы зададите запрос в неправильном формате или зададите один и тот же запрос дважды, вы получите вердикт «Неправильный ответ».</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></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 1 Yes</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 ! 1 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 0 3 No No No No No No</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нам задан город с тремя домами, в каждый из которых ведет по одной дороге. Решение участника задает запрос «<span class="tex-font-style-tt">? 1 2</span>», чтобы узнать, можно ли от дома $$$1$$$ добраться до дома $$$2$$$. Программа жюри отвечает «<span class="tex-font-style-tt">Yes</span>». После этого решение участника выводит ответ «<span class="tex-font-style-tt">! 1 2</span>» и завершается.</p><p>Во втором примере решение участника делает шесть различных запросов, убеждается в том, что пары домов, достижимых друг из друга, нет, и выводит «<span class="tex-font-style-tt">! 0 0</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:23</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bde1ef657a71',t:'MTY5NjY2NzAwMy4zODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2200"]
1498F
1498
F
ru
F. Рождественская игра
<div class="problem-statement"><div class="header"><div class="title">F. Рождественская игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб собираются отмечать Рождество, играя в игру с деревом подарков. Дерево состоит из $$$n$$$ вершин (пронумерованных от $$$1$$$ до $$$n$$$, вершина $$$r$$$ является корнем). На $$$i$$$-й вершине висят $$$a_i$$$ подарков.</p><p>Перед началом игры выбирается некоторое целое число $$$k$$$. Затем игра проходит следующим образом:</p><ul><li> Алиса начинает игру, затем ходы совершаются обоими игроками по очереди;</li><li> на каждом ходу текущий игрок выбирает некоторую вершину (например, $$$i$$$), которая находится на глубине хотя бы $$$k$$$. Затем игрок снимает некоторое положительное целое число подарков, которые висят на этой вершине, — назовем его $$$m$$$ $$$(1 \le m \le a_i)$$$;</li><li> затем игрок вешает эти $$$m$$$ подарков на $$$k$$$-го предка (назовем его $$$j$$$) $$$i$$$-й вершины ($$$k$$$-м предком вершины $$$i$$$ назовем такую вершину $$$j$$$, что $$$i$$$ — потомок $$$j$$$, а глубина $$$j$$$ ровно на $$$k$$$ меньше глубины $$$i$$$). Теперь количество подарков на $$$i$$$-й вершине $$$(a_i)$$$ уменьшилось на $$$m$$$, а $$$a_j$$$, соответственно, увеличилось на $$$m$$$;</li><li> Алиса и Боб играют оптимально. Тот, кто не может совершить ход, проигрывает.</li></ul><p><span class="tex-font-style-bf">Для каждого возможного корня</span> дерева сообщите, кто выиграет игру — Алиса или Боб.</p><p>Глубина вершины $$$i$$$ в дереве с корнем $$$r$$$ определяется, как количество ребер на простом пути из вершины $$$r$$$ до вершины $$$i$$$. Глубина корня $$$r$$$ равна нулю.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ $$$(3 \le n \le 10^5, 1 \le k \le 20)$$$.</p><p>В каждой из следующих $$$n-1$$$ строк записаны два целых числа $$$x$$$ и $$$y$$$ $$$(1 \le x, y \le n, x \neq y)$$$, описывающие неориентированное ребро между двумя вершинами $$$x$$$ и $$$y$$$. Эти ребра образуют дерево из $$$n$$$ вершин.</p><p>В следующей строке записаны $$$n$$$ целых чисел, задающих массив $$$a$$$ $$$(0 \le a_i \le 10^9)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, где $$$i$$$-е число равно $$$1$$$, если Алиса выиграет игру, если дерево подвешено за вершину $$$i$$$, и $$$0$$$ в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 2 1 3 5 2 4 3 0 3 2 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 0 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Посчитаем ответ для примера с корнем в 1 и в 2.</p><p><span class="tex-font-style-bf">Корень 1</span></p><p>Алиса всегда выигрывает в данном случае. Возможная игра между Алисой и Бобом выглядит так:</p><ul> <li> Алиса перемещает один подарок из вершины 4 в вершину 3. </li><li> Боб перемещает четыре подарка из вершины 5 в вершину 2. </li><li> Алиса перемещает четыре подарка из вершины 2 в вершину 1. </li><li> Боб перемещает три подарка из вершины 2 в вершину 1. </li><li> Алиса перемещает три подарка из вершины 3 в вершину 1. </li><li> Боб перемещает три подарка из вершины 4 в вершину 3. </li><li> Алиса перемещает три подарка из вершины 3 в вершину 1. </li></ul><p>Боб не может сделать ход, а потому проигрывает.</p><p><span class="tex-font-style-bf">Корень 2</span></p><p>Боб всегда выигрывает в данном случае. Пример игры:</p><ul> <li> Алиса перемещает четыре подарка из вершины 4 в вершину 3. </li><li> Боб перемещает четыре подарка из вершины 5 в вершину 2. </li><li> Алиса перемещает шесть подарков из вершины 3 в вершину 1. </li><li> Боб перемещает шесть подарков из вершины 1 в вершину 2. </li></ul><p>Алиса не может сделать ход, а потому проигрывает.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="8701d7afa2ea5494901516ed187922fc"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="8c78c7c6424e0dbb287a71c86cc81212c11d8de4"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8701d7afa2ea5494901516ed187922fc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1498%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='8701d7afa2ea5494901516ed187922fc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1498">CodeCraft-21 and Codeforces Round 711 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8701d7afa2ea5494901516ed187922fc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1498/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди"> игры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='8701d7afa2ea5494901516ed187922fc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="939727"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8701d7afa2ea5494901516ed187922fc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="939727"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89069" title="CodeCraft-21 and Codeforces Round #711 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13386" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89137" title="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13409" resourceName="CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1498">Задачи</a></li> <li><a href="/contest/1498/submit">Отослать</a></li> <li><a href="/contest/1498/my">Мои посылки</a></li> <li><a href="/contest/1498/status">Статус</a></li> <li><a href="/contest/1498/hacks">Взломы</a></li> <li><a href="/contest/1498/room/1">Комната</a></li> <li><a href="/contest/1498/standings">Положение</a></li> <li><a href="/contest/1498/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_212b63737b8f691a1696cf965c85fdb654f42547"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Рождественская игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб собираются отмечать Рождество, играя в игру с деревом подарков. Дерево состоит из $$$n$$$ вершин (пронумерованных от $$$1$$$ до $$$n$$$, вершина $$$r$$$ является корнем). На $$$i$$$-й вершине висят $$$a_i$$$ подарков.</p><p>Перед началом игры выбирается некоторое целое число $$$k$$$. Затем игра проходит следующим образом:</p><ul><li> Алиса начинает игру, затем ходы совершаются обоими игроками по очереди;</li><li> на каждом ходу текущий игрок выбирает некоторую вершину (например, $$$i$$$), которая находится на глубине хотя бы $$$k$$$. Затем игрок снимает некоторое положительное целое число подарков, которые висят на этой вершине, — назовем его $$$m$$$ $$$(1 \le m \le a_i)$$$;</li><li> затем игрок вешает эти $$$m$$$ подарков на $$$k$$$-го предка (назовем его $$$j$$$) $$$i$$$-й вершины ($$$k$$$-м предком вершины $$$i$$$ назовем такую вершину $$$j$$$, что $$$i$$$ — потомок $$$j$$$, а глубина $$$j$$$ ровно на $$$k$$$ меньше глубины $$$i$$$). Теперь количество подарков на $$$i$$$-й вершине $$$(a_i)$$$ уменьшилось на $$$m$$$, а $$$a_j$$$, соответственно, увеличилось на $$$m$$$;</li><li> Алиса и Боб играют оптимально. Тот, кто не может совершить ход, проигрывает.</li></ul><p><span class="tex-font-style-bf">Для каждого возможного корня</span> дерева сообщите, кто выиграет игру — Алиса или Боб.</p><p>Глубина вершины $$$i$$$ в дереве с корнем $$$r$$$ определяется, как количество ребер на простом пути из вершины $$$r$$$ до вершины $$$i$$$. Глубина корня $$$r$$$ равна нулю.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ $$$(3 \le n \le 10^5, 1 \le k \le 20)$$$.</p><p>В каждой из следующих $$$n-1$$$ строк записаны два целых числа $$$x$$$ и $$$y$$$ $$$(1 \le x, y \le n, x \neq y)$$$, описывающие неориентированное ребро между двумя вершинами $$$x$$$ и $$$y$$$. Эти ребра образуют дерево из $$$n$$$ вершин.</p><p>В следующей строке записаны $$$n$$$ целых чисел, задающих массив $$$a$$$ $$$(0 \le a_i \le 10^9)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, где $$$i$$$-е число равно $$$1$$$, если Алиса выиграет игру, если дерево подвешено за вершину $$$i$$$, и $$$0$$$ в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 2 1 3 5 2 4 3 0 3 2 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 0 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Посчитаем ответ для примера с корнем в 1 и в 2.</p><p><span class="tex-font-style-bf">Корень 1</span></p><p>Алиса всегда выигрывает в данном случае. Возможная игра между Алисой и Бобом выглядит так:</p><ul> <li> Алиса перемещает один подарок из вершины 4 в вершину 3. </li><li> Боб перемещает четыре подарка из вершины 5 в вершину 2. </li><li> Алиса перемещает четыре подарка из вершины 2 в вершину 1. </li><li> Боб перемещает три подарка из вершины 2 в вершину 1. </li><li> Алиса перемещает три подарка из вершины 3 в вершину 1. </li><li> Боб перемещает три подарка из вершины 4 в вершину 3. </li><li> Алиса перемещает три подарка из вершины 3 в вершину 1. </li></ul><p>Боб не может сделать ход, а потому проигрывает.</p><p><span class="tex-font-style-bf">Корень 2</span></p><p>Боб всегда выигрывает в данном случае. Пример игры:</p><ul> <li> Алиса перемещает четыре подарка из вершины 4 в вершину 3. </li><li> Боб перемещает четыре подарка из вершины 5 в вершину 2. </li><li> Алиса перемещает шесть подарков из вершины 3 в вершину 1. </li><li> Боб перемещает шесть подарков из вершины 1 в вершину 2. </li></ul><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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:24</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bdeacefa3a56',t:'MTY5NjY2NzAwNC43MTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0438\u0433\u0440\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2500"]
1499A
1499
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>У вас есть игральная доска, которую можно представить в виде поля из $$$2 \times n$$$ клеток.</p><p>Первые $$$k_1$$$ клеток на первой строке и первые $$$k_2$$$ клеток на второй строке покрашены в белый. Все остальные клетки окрашены в черный.</p><p>У вас есть $$$w$$$ белых доминошек (плитки $$$2 \times 1$$$, обе клетки которых белые) и $$$b$$$ черных доминошек (плитки $$$2 \times 1$$$, обе клетки которых черные).</p><p>Вы можете положить белую доминошку на доску, если обе клетки доски под ней белые и не заняты другими доминошками. Аналогично, вы можете положить черную доминошку на доску, если обе клетки доски под ней черные и не заняты другими доминошками.</p><p>Можете ли вы положить все $$$w + b$$$ доминошек на доску, если вы можете класть доминошки как вертикально, так и горизонтально?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 3000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных заданы три целых числа $$$n$$$, $$$k_1$$$ и $$$k_2$$$ ($$$1 \le n \le 1000$$$; $$$0 \le k_1, k_2 \le n$$$).</p><p>Во второй строке каждого набора заданы два целых числа $$$w$$$ и $$$b$$$ ($$$0 \le w, b \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите <span class="tex-font-style-tt">YES</span>, если возможно уложить все $$$w + b$$$ доминошек на доску, или <span class="tex-font-style-tt">NO</span> в противном случае.</p><p>Вы можете вывести каждую букву в любом регистре (например, <span class="tex-font-style-tt">YES</span>, <span class="tex-font-style-tt">Yes</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">yEs</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 0 1 1 0 1 1 1 0 0 3 0 0 1 3 4 3 1 2 2 5 4 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES NO YES YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, $$$n = 1$$$, $$$k_1 = 0$$$ и $$$k_2 = 1$$$. Следовательно, у доски $$$2 \times 1$$$ клетка $$$(1, 1)$$$ — черная, а $$$(2, 1)$$$ — белая. Таким образом, вы не можете положить ни одной белой доминошки, так как только одна клетка доски белая.</p><p>Во втором наборе, доска того же размера $$$2 \times 1$$$, но обе клетки — белые. Так как $$$w = 0$$$ и $$$b = 0$$$, то вы можете уложить $$$0 + 0 = 0$$$ доминошек на доску.</p><p>В третьем наборе, доска $$$2 \times 3$$$, но полностью покрашена в черный (так как $$$k_1 = k_2 = 0$$$), а потому вы не можете уложить ни одной белой доминошки.</p><p>В четвертом наборе, клетки $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$ и $$$(2, 1)$$$ — белые, а все остальные — черные. Вы можете уложить $$$2$$$ белые доминошки на позиции $$$((1, 1), (2, 1))$$$ и $$$((1, 2), (1, 3))$$$, и $$$2$$$ черные доминошки на позиции $$$((1, 4), (2, 4))$$$ $$$((2, 2), (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="df165fed1e4da0e0be41f5984fd416e8"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='df165fed1e4da0e0be41f5984fd416e8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='df165fed1e4da0e0be41f5984fd416e8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='df165fed1e4da0e0be41f5984fd416e8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='df165fed1e4da0e0be41f5984fd416e8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928249"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='df165fed1e4da0e0be41f5984fd416e8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928249"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_08fa30a65006f0224aa7d675675c2e3ddc943000"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>У вас есть игральная доска, которую можно представить в виде поля из $$$2 \times n$$$ клеток.</p><p>Первые $$$k_1$$$ клеток на первой строке и первые $$$k_2$$$ клеток на второй строке покрашены в белый. Все остальные клетки окрашены в черный.</p><p>У вас есть $$$w$$$ белых доминошек (плитки $$$2 \times 1$$$, обе клетки которых белые) и $$$b$$$ черных доминошек (плитки $$$2 \times 1$$$, обе клетки которых черные).</p><p>Вы можете положить белую доминошку на доску, если обе клетки доски под ней белые и не заняты другими доминошками. Аналогично, вы можете положить черную доминошку на доску, если обе клетки доски под ней черные и не заняты другими доминошками.</p><p>Можете ли вы положить все $$$w + b$$$ доминошек на доску, если вы можете класть доминошки как вертикально, так и горизонтально?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 3000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных заданы три целых числа $$$n$$$, $$$k_1$$$ и $$$k_2$$$ ($$$1 \le n \le 1000$$$; $$$0 \le k_1, k_2 \le n$$$).</p><p>Во второй строке каждого набора заданы два целых числа $$$w$$$ и $$$b$$$ ($$$0 \le w, b \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите <span class="tex-font-style-tt">YES</span>, если возможно уложить все $$$w + b$$$ доминошек на доску, или <span class="tex-font-style-tt">NO</span> в противном случае.</p><p>Вы можете вывести каждую букву в любом регистре (например, <span class="tex-font-style-tt">YES</span>, <span class="tex-font-style-tt">Yes</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">yEs</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 0 1 1 0 1 1 1 0 0 3 0 0 1 3 4 3 1 2 2 5 4 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES NO YES YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, $$$n = 1$$$, $$$k_1 = 0$$$ и $$$k_2 = 1$$$. Следовательно, у доски $$$2 \times 1$$$ клетка $$$(1, 1)$$$ — черная, а $$$(2, 1)$$$ — белая. Таким образом, вы не можете положить ни одной белой доминошки, так как только одна клетка доски белая.</p><p>Во втором наборе, доска того же размера $$$2 \times 1$$$, но обе клетки — белые. Так как $$$w = 0$$$ и $$$b = 0$$$, то вы можете уложить $$$0 + 0 = 0$$$ доминошек на доску.</p><p>В третьем наборе, доска $$$2 \times 3$$$, но полностью покрашена в черный (так как $$$k_1 = k_2 = 0$$$), а потому вы не можете уложить ни одной белой доминошки.</p><p>В четвертом наборе, клетки $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$ и $$$(2, 1)$$$ — белые, а все остальные — черные. Вы можете уложить $$$2$$$ белые доминошки на позиции $$$((1, 1), (2, 1))$$$ и $$$((1, 2), (1, 3))$$$, и $$$2$$$ черные доминошки на позиции $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:26</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bdf32f3a75b3',t:'MTY5NjY2NzAwNi4yMTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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\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", "*800"]
1499B
1499
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">0</span>' или '<span class="tex-font-style-tt">1</span>'. Пусть $$$|s|$$$ будет длиной строки $$$s$$$.</p><p>Требуется выбрать некоторое целое число $$$k$$$ ($$$k &gt; 0$$$) и последовательность $$$a$$$ длины $$$k$$$ такую что: </p><ul> <li> $$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_k \le |s|$$$; </li><li> $$$a_{i-1} + 1 &lt; a_i$$$ для всех $$$i$$$ от $$$2$$$ до $$$k$$$. </li></ul><p>Символы на позициях $$$a_1, a_2, \dots, a_k$$$ удаляются, оставшиеся символы склеиваются без изменения порядка. То есть, другими словами, позиции в выбранной последовательности $$$a$$$ не должны быть соседними.</p><p>Пусть полученная строка будет $$$s'$$$. $$$s'$$$ называется отсортированной, если для всех $$$i$$$ от $$$2$$$ до $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.</p><p>Существует ли такая последовательность $$$a$$$, что $$$s'$$$ отсортирована?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Затем следует описание $$$t$$$ наборов входных данных.</p><p>В единственной строке каждого набора входных данных содержится строка $$$s$$$ ($$$2 \le |s| \le 100$$$). Каждый символ равен либо '<span class="tex-font-style-tt">0</span>', либо '<span class="tex-font-style-tt">1</span>'.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите «<span class="tex-font-style-tt">YES</span>», если существует такая последовательность $$$a$$$, что при удалении символов на позициях $$$a_1, a_2, \dots, a_k$$$ и склеивании оставшихся частей без изменения порядка получится отсортированная строка.</p><p>В противном случае выведите «<span class="tex-font-style-tt">NO</span>».</p><p>Вы можете вывести каждую букву в любом регистре (например, <span class="tex-font-style-tt">YES</span>, <span class="tex-font-style-tt">Yes</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">yEs</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 10101011011 0000 11111 110 1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно выбрать последовательность $$$a=[1,3,6,9]$$$. При удалении подчеркнутых букв из «<span class="tex-font-style-tt"><span class="tex-font-style-underline">1</span>0<span class="tex-font-style-underline">1</span>01<span class="tex-font-style-underline">0</span>11<span class="tex-font-style-underline">0</span>11</span>» получится строка «<span class="tex-font-style-tt">0011111</span>», которая отсортирована.</p><p>Во втором и в третьем наборах входных данных последовательность уже отсортирована.</p><p>В четвертом наборе входных данных можно выбрать последовательность $$$a=[3]$$$. $$$s'=$$$ «<span class="tex-font-style-tt">11</span>», которая отсортирована.</p><p>В пятом наборе входных данных нет способа выбрать последовательность $$$a$$$ так, чтобы $$$s'$$$ была отсортирована.</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="b8e0964160b1c4ec172b3b816eb247aa"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b8e0964160b1c4ec172b3b816eb247aa'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='b8e0964160b1c4ec172b3b816eb247aa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b8e0964160b1c4ec172b3b816eb247aa'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='b8e0964160b1c4ec172b3b816eb247aa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928250"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b8e0964160b1c4ec172b3b816eb247aa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928250"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_68bb5ae748e4411f7911e42d43900d21a4768e7f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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">0</span>' или '<span class="tex-font-style-tt">1</span>'. Пусть $$$|s|$$$ будет длиной строки $$$s$$$.</p><p>Требуется выбрать некоторое целое число $$$k$$$ ($$$k &gt; 0$$$) и последовательность $$$a$$$ длины $$$k$$$ такую что: </p><ul> <li> $$$1 \le a_1 &lt; a_2 &lt; \dots &lt; a_k \le |s|$$$; </li><li> $$$a_{i-1} + 1 &lt; a_i$$$ для всех $$$i$$$ от $$$2$$$ до $$$k$$$. </li></ul><p>Символы на позициях $$$a_1, a_2, \dots, a_k$$$ удаляются, оставшиеся символы склеиваются без изменения порядка. То есть, другими словами, позиции в выбранной последовательности $$$a$$$ не должны быть соседними.</p><p>Пусть полученная строка будет $$$s'$$$. $$$s'$$$ называется отсортированной, если для всех $$$i$$$ от $$$2$$$ до $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.</p><p>Существует ли такая последовательность $$$a$$$, что $$$s'$$$ отсортирована?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Затем следует описание $$$t$$$ наборов входных данных.</p><p>В единственной строке каждого набора входных данных содержится строка $$$s$$$ ($$$2 \le |s| \le 100$$$). Каждый символ равен либо '<span class="tex-font-style-tt">0</span>', либо '<span class="tex-font-style-tt">1</span>'.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите «<span class="tex-font-style-tt">YES</span>», если существует такая последовательность $$$a$$$, что при удалении символов на позициях $$$a_1, a_2, \dots, a_k$$$ и склеивании оставшихся частей без изменения порядка получится отсортированная строка.</p><p>В противном случае выведите «<span class="tex-font-style-tt">NO</span>».</p><p>Вы можете вывести каждую букву в любом регистре (например, <span class="tex-font-style-tt">YES</span>, <span class="tex-font-style-tt">Yes</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">yEs</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 10101011011 0000 11111 110 1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно выбрать последовательность $$$a=[1,3,6,9]$$$. При удалении подчеркнутых букв из «<span class="tex-font-style-tt"><span class="tex-font-style-underline">1</span>0<span class="tex-font-style-underline">1</span>01<span class="tex-font-style-underline">0</span>11<span class="tex-font-style-underline">0</span>11</span>» получится строка «<span class="tex-font-style-tt">0011111</span>», которая отсортирована.</p><p>Во втором и в третьем наборах входных данных последовательность уже отсортирована.</p><p>В четвертом наборе входных данных можно выбрать последовательность $$$a=[3]$$$. $$$s'=$$$ «<span class="tex-font-style-tt">11</span>», которая отсортирована.</p><p>В пятом наборе входных данных нет способа выбрать последовательность $$$a$$$ так, чтобы $$$s'$$$ была отсортирована.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:27</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bdfc997216af',t:'MTY5NjY2NzAwNy42MDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"]
1499C
1499
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>Предположим, вы стоите на плоскости $$$XY$$$ в точке $$$(0, 0)$$$ и хотите попасть в точку $$$(n, n)$$$.</p><p>Вы можете двигать только в двух направлениях: </p><ul> <li> <span class="tex-font-style-it">вправо</span>, т. е. горизонтально и в направлении увеличения $$$x$$$ коодинаты, </li><li> или <span class="tex-font-style-it">вверх</span>, т. е. вертикально и в направлении увеличения $$$y$$$ координаты. </li></ul><p>Другими словами, ваш путь имеет следующую структуру: </p><ul> <li> первоначально, вы выбираете: пойти вправо или вверх; </li><li> далее вы проходите некоторое <span class="tex-font-style-bf">положительное целое</span> расстояние в выбранном направлении (расстояния можно выбирать независимо); </li><li> далее вы меняете направление движения (от «вправо» к «вверх», либо от «вверх» к «вправо») и повторяете процесс. </li></ul><p>Вам не нравится менять свое направление слишком много раз, а потому вы сделаете не более $$$n - 1$$$ изменений направления.</p><p>В результате ваш путь будет представлять ломаную от $$$(0, 0)$$$ к $$$(n, n)$$$, состоящую из <span class="tex-font-style-bf">не более</span> чем $$$n$$$ отрезков, каждый из которых имеет положительную целую длину, а также вертикальные и горизонтальные отрезки идут по очереди.</p><p>Не все пути равны. У вас есть $$$n$$$ целых чисел $$$c_1, c_2, \dots, c_n$$$, где $$$c_i$$$ — это цена $$$i$$$-го отрезка.</p><p>Используя эти цены, можно определить <span class="tex-font-style-it">цену пути</span> как сумму длин отрезков этого пути умноженных на их стоимости, т. е. если путь состоит из $$$k$$$ отрезков ($$$k \le n$$$), то цена пути равна $$$\sum\limits_{i=1}^{k}{c_i \cdot length_i}$$$ (отрезки нумеруются от $$$1$$$ по $$$k$$$ в порядке их обхода).</p><p>Определите путь минимальной стоимости и выведите его цену.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$).</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^9$$$) — цены каждого отрезка.</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных вы должны вывести минимальную цену пути из $$$(0, 0)$$$ в $$$(n, n)$$$, состоящего из не более $$$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 2 13 88 3 2 3 1 5 4 3 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 202 13 19 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия, чтобы достигнуть $$$(2, 2)$$$, нужно сделать хотя бы один поворот, и путь может состоять из $$$2$$$ отрезков: горизонтального длины $$$2$$$ и вертикального длины $$$2$$$. Стоимость равна $$$2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$$$.</p><p>Во втором примере можно построить путь из $$$3$$$ отрезков: длины $$$1$$$, длины $$$3$$$ и длины $$$2$$$. Стоимость равна $$$1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$$$.</p><p>В третьем примере можно построить путь из $$$4$$$ отрезков: длины $$$1$$$, длины $$$1$$$, длины $$$4$$$ и длины $$$4$$$. Стоимость равна $$$1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="85691a30fd25c9c394f010f9dc767a93"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='85691a30fd25c9c394f010f9dc767a93'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='85691a30fd25c9c394f010f9dc767a93'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='85691a30fd25c9c394f010f9dc767a93'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='85691a30fd25c9c394f010f9dc767a93'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928251"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='85691a30fd25c9c394f010f9dc767a93'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928251"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_fd81c86d6928a8bb1d2360d2c69ea1903e4462cd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Предположим, вы стоите на плоскости $$$XY$$$ в точке $$$(0, 0)$$$ и хотите попасть в точку $$$(n, n)$$$.</p><p>Вы можете двигать только в двух направлениях: </p><ul> <li> <span class="tex-font-style-it">вправо</span>, т. е. горизонтально и в направлении увеличения $$$x$$$ коодинаты, </li><li> или <span class="tex-font-style-it">вверх</span>, т. е. вертикально и в направлении увеличения $$$y$$$ координаты. </li></ul><p>Другими словами, ваш путь имеет следующую структуру: </p><ul> <li> первоначально, вы выбираете: пойти вправо или вверх; </li><li> далее вы проходите некоторое <span class="tex-font-style-bf">положительное целое</span> расстояние в выбранном направлении (расстояния можно выбирать независимо); </li><li> далее вы меняете направление движения (от «вправо» к «вверх», либо от «вверх» к «вправо») и повторяете процесс. </li></ul><p>Вам не нравится менять свое направление слишком много раз, а потому вы сделаете не более $$$n - 1$$$ изменений направления.</p><p>В результате ваш путь будет представлять ломаную от $$$(0, 0)$$$ к $$$(n, n)$$$, состоящую из <span class="tex-font-style-bf">не более</span> чем $$$n$$$ отрезков, каждый из которых имеет положительную целую длину, а также вертикальные и горизонтальные отрезки идут по очереди.</p><p>Не все пути равны. У вас есть $$$n$$$ целых чисел $$$c_1, c_2, \dots, c_n$$$, где $$$c_i$$$ — это цена $$$i$$$-го отрезка.</p><p>Используя эти цены, можно определить <span class="tex-font-style-it">цену пути</span> как сумму длин отрезков этого пути умноженных на их стоимости, т. е. если путь состоит из $$$k$$$ отрезков ($$$k \le n$$$), то цена пути равна $$$\sum\limits_{i=1}^{k}{c_i \cdot length_i}$$$ (отрезки нумеруются от $$$1$$$ по $$$k$$$ в порядке их обхода).</p><p>Определите путь минимальной стоимости и выведите его цену.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$).</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^9$$$) — цены каждого отрезка.</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных вы должны вывести минимальную цену пути из $$$(0, 0)$$$ в $$$(n, n)$$$, состоящего из не более $$$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 2 13 88 3 2 3 1 5 4 3 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 202 13 19 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия, чтобы достигнуть $$$(2, 2)$$$, нужно сделать хотя бы один поворот, и путь может состоять из $$$2$$$ отрезков: горизонтального длины $$$2$$$ и вертикального длины $$$2$$$. Стоимость равна $$$2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$$$.</p><p>Во втором примере можно построить путь из $$$3$$$ отрезков: длины $$$1$$$, длины $$$3$$$ и длины $$$2$$$. Стоимость равна $$$1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$$$.</p><p>В третьем примере можно построить путь из $$$4$$$ отрезков: длины $$$1$$$, длины $$$1$$$, длины $$$4$$$ и длины $$$4$$$. Стоимость равна $$$1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$$$.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:29</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be053ef79d75',t:'MTY5NjY2NzAwOS4xMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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", "*1500"]
1499D
1499
D
ru
D. Количество пар
<div class="problem-statement"><div class="header"><div class="title">D. Количество пар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны три положительных (больше нуля) целых числа $$$c$$$, $$$d$$$ и $$$x$$$.</p><p>Вы должны найти количество пар положительных целых чисел $$$(a, b)$$$ таких, что выполняется равенство $$$c \cdot lcm(a, b) - d \cdot gcd(a, b) = x$$$. Где $$$lcm(a, b)$$$ — наименьшее общее кратное $$$a$$$ и $$$b$$$, а $$$gcd(a, b)$$$ — наибольший общий делитель $$$a$$$ и $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из одной строки, содержащей три целых числа $$$c$$$, $$$d$$$ и $$$x$$$ ($$$1 \le c, d, x \le 10^7$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите одно целое число — количество пар ($$$a, b$$$), таких, что выполняется вышеописанное равенство.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 3 4 2 6 3 3 7 2 7 25 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 0 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере корректные пары: ($$$1, 4$$$), ($$$4,1$$$), ($$$3, 6$$$), ($$$6, 3$$$).</p><p>Во втором примере корректные пары: ($$$1, 2$$$), ($$$2, 1$$$), ($$$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="537bbd21ed4c286b4e590d4d0e6923fc"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='537bbd21ed4c286b4e590d4d0e6923fc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='537bbd21ed4c286b4e590d4d0e6923fc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='537bbd21ed4c286b4e590d4d0e6923fc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='537bbd21ed4c286b4e590d4d0e6923fc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928252"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='537bbd21ed4c286b4e590d4d0e6923fc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928252"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_19540fd98cfe04bb44c0462d0a1496a0772d2e04"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Количество пар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны три положительных (больше нуля) целых числа $$$c$$$, $$$d$$$ и $$$x$$$.</p><p>Вы должны найти количество пар положительных целых чисел $$$(a, b)$$$ таких, что выполняется равенство $$$c \cdot lcm(a, b) - d \cdot gcd(a, b) = x$$$. Где $$$lcm(a, b)$$$ — наименьшее общее кратное $$$a$$$ и $$$b$$$, а $$$gcd(a, b)$$$ — наибольший общий делитель $$$a$$$ и $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из одной строки, содержащей три целых числа $$$c$$$, $$$d$$$ и $$$x$$$ ($$$1 \le c, d, x \le 10^7$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового случая выведите одно целое число — количество пар ($$$a, b$$$), таких, что выполняется вышеописанное равенство.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 3 4 2 6 3 3 7 2 7 25 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 0 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере корректные пары: ($$$1, 4$$$), ($$$4,1$$$), ($$$3, 6$$$), ($$$6, 3$$$).</p><p>Во втором примере корректные пары: ($$$1, 2$$$), ($$$2, 1$$$), ($$$3, 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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:30</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be0ebbe016b7',t:'MTY5NjY2NzAxMC40NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\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\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2100"]
1499E
1499
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>Заданы две строки $$$x$$$ и $$$y$$$, обе состоят из строчных латинских букв. Пусть $$$|s|$$$ будет длиной строки $$$s$$$.</p><p>Назовем последовательность $$$a$$$ последовательностью слияния, если она состоит из ровно $$$|x|$$$ нулей и ровно $$$|y|$$$ единиц в некотором порядке.</p><p>Слияние $$$z$$$ получается из последовательности $$$a$$$ по следующим правилам: </p><ul> <li> если $$$a_i=0$$$, то удалить букву из начала $$$x$$$ и приписать ее в конец $$$z$$$; </li><li> если $$$a_i=1$$$, то удалить букву из начала $$$y$$$ и приписать ее в конец $$$z$$$. </li></ul><p>Две последовательности слияния $$$a$$$ и $$$b$$$ считаются различными, если существует такая позиция $$$i$$$, что $$$a_i \neq b_i$$$.</p><p>Назовем строку $$$z$$$ <span class="tex-font-style-it">хаотичной</span>, если для всех $$$i$$$ от $$$2$$$ до $$$|z|$$$ $$$z_{i-1} \neq z_i$$$.</p><p>Пусть $$$s[l,r]$$$ для некоторых $$$1 \le l \le r \le |s|$$$ будет подстрокой последовательных букв $$$s$$$, начинающейся с позиции $$$l$$$ и заканчивающейся в позиции $$$r$$$ включительно.</p><p>Пусть $$$f(l_1, r_1, l_2, r_2)$$$ будет количеством различных последовательностей слияния $$$x[l_1,r_1]$$$ и $$$y[l_2,r_2]$$$, которые производят <span class="tex-font-style-it">хаотичные</span> слияния. Обратите внимание, что рассматриваются только непустые подстроки $$$x$$$ и $$$y$$$.</p><p>Посчитайте $$$\sum \limits_{1 \le l_1 \le r_1 \le |x| \\ 1 \le l_2 \le r_2 \le |y|} f(l_1, r_1, l_2, r_2)$$$. Выведите ответ по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записана строка $$$x$$$ ($$$1 \le |x| \le 1000$$$).</p><p>Во второй строке записана строка $$$y$$$ ($$$1 \le |y| \le 1000$$$).</p><p>Обе строки состоят только из строчных латинских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — сумму $$$f(l_1, r_1, l_2, r_2)$$$ по $$$1 \le l_1 \le r_1 \le |x|$$$ и $$$1 \le l_2 \le r_2 \le |y|$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> aaa bb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24 </pre></div><div class="input"><div class="title">Входные данные</div><pre> code forces </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1574 </pre></div><div class="input"><div class="title">Входные данные</div><pre> aaaaa aaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> justamassivetesttocheck howwellyouhandlemodulooperations </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 667387032 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере: </p><ul> <li> $$$6$$$ пар подстрок «<span class="tex-font-style-tt">a</span>» and «<span class="tex-font-style-tt">b</span>», каждая с корректными последовательностями слияния «<span class="tex-font-style-tt">01</span>» and «<span class="tex-font-style-tt">10</span>»; </li><li> $$$3$$$ пары подстрок «<span class="tex-font-style-tt">a</span>» and «<span class="tex-font-style-tt">bb</span>», каждая с корректной последовательностью слияния «<span class="tex-font-style-tt">101</span>»; </li><li> $$$4$$$ пары подстрок «<span class="tex-font-style-tt">aa</span>» and «<span class="tex-font-style-tt">b</span>», каждая с корректной последовательностью слияния «<span class="tex-font-style-tt">010</span>»; </li><li> $$$2$$$ пары подстрок «<span class="tex-font-style-tt">aa</span>» and «<span class="tex-font-style-tt">bb</span>», каждая с корректными последовательностями слияния «<span class="tex-font-style-tt">0101</span>» and «<span class="tex-font-style-tt">1010</span>»; </li><li> $$$2$$$ пары подстрок «<span class="tex-font-style-tt">aaa</span>» and «<span class="tex-font-style-tt">b</span>», каждая без корректных последовательностей слияния; </li><li> $$$1$$$ пара подстрок «<span class="tex-font-style-tt">aaa</span>» and «<span class="tex-font-style-tt">bb</span>» с корректной последовательностью слияния «<span class="tex-font-style-tt">01010</span>». </li></ul><p>Поэтому ответ равен $$$6 \cdot 2 + 3 \cdot 1 + 4 \cdot 1 + 2 \cdot 2 + 2 \cdot 0 + 1 \cdot 1 = 24$$$.</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="71e712fec91797c58a1e5bfe053059aa"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='71e712fec91797c58a1e5bfe053059aa'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='71e712fec91797c58a1e5bfe053059aa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='71e712fec91797c58a1e5bfe053059aa'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='71e712fec91797c58a1e5bfe053059aa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928253"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='71e712fec91797c58a1e5bfe053059aa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928253"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_18e76ed6b5af1985af9210c258b1ac51226a451b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Заданы две строки $$$x$$$ и $$$y$$$, обе состоят из строчных латинских букв. Пусть $$$|s|$$$ будет длиной строки $$$s$$$.</p><p>Назовем последовательность $$$a$$$ последовательностью слияния, если она состоит из ровно $$$|x|$$$ нулей и ровно $$$|y|$$$ единиц в некотором порядке.</p><p>Слияние $$$z$$$ получается из последовательности $$$a$$$ по следующим правилам: </p><ul> <li> если $$$a_i=0$$$, то удалить букву из начала $$$x$$$ и приписать ее в конец $$$z$$$; </li><li> если $$$a_i=1$$$, то удалить букву из начала $$$y$$$ и приписать ее в конец $$$z$$$. </li></ul><p>Две последовательности слияния $$$a$$$ и $$$b$$$ считаются различными, если существует такая позиция $$$i$$$, что $$$a_i \neq b_i$$$.</p><p>Назовем строку $$$z$$$ <span class="tex-font-style-it">хаотичной</span>, если для всех $$$i$$$ от $$$2$$$ до $$$|z|$$$ $$$z_{i-1} \neq z_i$$$.</p><p>Пусть $$$s[l,r]$$$ для некоторых $$$1 \le l \le r \le |s|$$$ будет подстрокой последовательных букв $$$s$$$, начинающейся с позиции $$$l$$$ и заканчивающейся в позиции $$$r$$$ включительно.</p><p>Пусть $$$f(l_1, r_1, l_2, r_2)$$$ будет количеством различных последовательностей слияния $$$x[l_1,r_1]$$$ и $$$y[l_2,r_2]$$$, которые производят <span class="tex-font-style-it">хаотичные</span> слияния. Обратите внимание, что рассматриваются только непустые подстроки $$$x$$$ и $$$y$$$.</p><p>Посчитайте $$$\sum \limits_{1 \le l_1 \le r_1 \le |x| \\ 1 \le l_2 \le r_2 \le |y|} f(l_1, r_1, l_2, r_2)$$$. Выведите ответ по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записана строка $$$x$$$ ($$$1 \le |x| \le 1000$$$).</p><p>Во второй строке записана строка $$$y$$$ ($$$1 \le |y| \le 1000$$$).</p><p>Обе строки состоят только из строчных латинских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — сумму $$$f(l_1, r_1, l_2, r_2)$$$ по $$$1 \le l_1 \le r_1 \le |x|$$$ и $$$1 \le l_2 \le r_2 \le |y|$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> aaa bb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24 </pre></div><div class="input"><div class="title">Входные данные</div><pre> code forces </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1574 </pre></div><div class="input"><div class="title">Входные данные</div><pre> aaaaa aaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> justamassivetesttocheck howwellyouhandlemodulooperations </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 667387032 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере: </p><ul> <li> $$$6$$$ пар подстрок «<span class="tex-font-style-tt">a</span>» and «<span class="tex-font-style-tt">b</span>», каждая с корректными последовательностями слияния «<span class="tex-font-style-tt">01</span>» and «<span class="tex-font-style-tt">10</span>»; </li><li> $$$3$$$ пары подстрок «<span class="tex-font-style-tt">a</span>» and «<span class="tex-font-style-tt">bb</span>», каждая с корректной последовательностью слияния «<span class="tex-font-style-tt">101</span>»; </li><li> $$$4$$$ пары подстрок «<span class="tex-font-style-tt">aa</span>» and «<span class="tex-font-style-tt">b</span>», каждая с корректной последовательностью слияния «<span class="tex-font-style-tt">010</span>»; </li><li> $$$2$$$ пары подстрок «<span class="tex-font-style-tt">aa</span>» and «<span class="tex-font-style-tt">bb</span>», каждая с корректными последовательностями слияния «<span class="tex-font-style-tt">0101</span>» and «<span class="tex-font-style-tt">1010</span>»; </li><li> $$$2$$$ пары подстрок «<span class="tex-font-style-tt">aaa</span>» and «<span class="tex-font-style-tt">b</span>», каждая без корректных последовательностей слияния; </li><li> $$$1$$$ пара подстрок «<span class="tex-font-style-tt">aaa</span>» and «<span class="tex-font-style-tt">bb</span>» с корректной последовательностью слияния «<span class="tex-font-style-tt">01010</span>». </li></ul><p>Поэтому ответ равен $$$6 \cdot 2 + 3 \cdot 1 + 4 \cdot 1 + 2 \cdot 2 + 2 \cdot 0 + 1 \cdot 1 = 24$$$.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:31</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be172ed7164b',t:'MTY5NjY2NzAxMS44MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\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", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2400"]
1499F
1499
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>Задано целое число $$$k$$$ и неориентированное дерево, состоящее из $$$n$$$ вершин.</p><p>Длина простого пути (пути, в котором каждая вершина встречается не более одного раза) между некоторой парой вершин равна количеству ребер в данном пути. Диаметр дерева равен максимальной длине пути между всеми парами вершин в дереве.</p><p>Вы планируете удалить множество ребер из дерева. Когда ребра удаляются, дерево распадается на несколько меньших деревьев. Множество ребер считается корректным, если у всех полученных деревьев диаметр меньше либо равен $$$k$$$.</p><p>Два множества ребер считаются различными, если существует такое ребро, что оно встречается только в одном из множеств.</p><p>Посчитайте количество корректных множеств ребер по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 5000$$$, $$$0 \le k \le n - 1$$$) — количество вершин в дереве и максимальный разрешенный диаметр, соответственно.</p><p>В каждой из следующих $$$n-1$$$ строк содержится описание ребра: два целых числа $$$v$$$ и $$$u$$$ ($$$1 \le v, u \le n$$$, $$$v \neq u$$$).</p><p>Заданные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество корректных множеств ребер по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 1 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 6 2 4 2 6 3 6 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 3 1 2 1 5 2 3 3 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 29 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере диаметр заданного дерева уже меньше либо равен $$$k$$$. Поэтому можно выбрать любое множество ребер, и в полученных деревьях диаметры будут меньше либо равны $$$k$$$. Всего есть $$$2^3$$$ множеств, включая пустое.</p><p>Во втором примере нужно удалить единственное ребро. Иначе диаметр будет $$$1$$$, что больше $$$0$$$.</p><p>Деревья для третьего и четвертого примеров: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b32002c8fe21ac9d1296f3e4664b38c1d955c580.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="7c89d02a016650a7e2e07217bfcd719c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7c89d02a016650a7e2e07217bfcd719c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='7c89d02a016650a7e2e07217bfcd719c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='7c89d02a016650a7e2e07217bfcd719c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='7c89d02a016650a7e2e07217bfcd719c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928254"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7c89d02a016650a7e2e07217bfcd719c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928254"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_de776fc59368c6fe723a92dee45d3efc0598eb02"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Задано целое число $$$k$$$ и неориентированное дерево, состоящее из $$$n$$$ вершин.</p><p>Длина простого пути (пути, в котором каждая вершина встречается не более одного раза) между некоторой парой вершин равна количеству ребер в данном пути. Диаметр дерева равен максимальной длине пути между всеми парами вершин в дереве.</p><p>Вы планируете удалить множество ребер из дерева. Когда ребра удаляются, дерево распадается на несколько меньших деревьев. Множество ребер считается корректным, если у всех полученных деревьев диаметр меньше либо равен $$$k$$$.</p><p>Два множества ребер считаются различными, если существует такое ребро, что оно встречается только в одном из множеств.</p><p>Посчитайте количество корректных множеств ребер по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 5000$$$, $$$0 \le k \le n - 1$$$) — количество вершин в дереве и максимальный разрешенный диаметр, соответственно.</p><p>В каждой из следующих $$$n-1$$$ строк содержится описание ребра: два целых числа $$$v$$$ и $$$u$$$ ($$$1 \le v, u \le n$$$, $$$v \neq u$$$).</p><p>Заданные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество корректных множеств ребер по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 2 1 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 0 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 6 2 4 2 6 3 6 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 3 1 2 1 5 2 3 3 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 29 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере диаметр заданного дерева уже меньше либо равен $$$k$$$. Поэтому можно выбрать любое множество ребер, и в полученных деревьях диаметры будут меньше либо равны $$$k$$$. Всего есть $$$2^3$$$ множеств, включая пустое.</p><p>Во втором примере нужно удалить единственное ребро. Иначе диаметр будет $$$1$$$, что больше $$$0$$$.</p><p>Деревья для третьего и четвертого примеров: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b32002c8fe21ac9d1296f3e4664b38c1d955c580.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:33</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be1fb94a149c',t:'MTY5NjY2NzAxMy4yMjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2400"]
1499G
1499
G
ru
G. Раскраска графа
<div class="problem-statement"><div class="header"><div class="title">G. Раскраска графа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>Вам дан двудольный граф, состоящий из $$$n_1$$$ вершин в первой доле и $$$n_2$$$ вершин во второй доле и $$$m$$$ ребер, пронумерованных от $$$1$$$ до $$$m$$$. Вы должны раскрасить каждые ребро в один из двух цветов, красный и синий. Необходимо минимизировать следующее значение: $$$\sum \limits_{v \in V} |r(v) - b(v)|$$$, где $$$V$$$ — множество вершин графа, $$$r(v)$$$ — число красных ребер, инцидентных $$$v$$$, и $$$b(v)$$$ — число синих ребер, инцидентных $$$v$$$.</p><p>Звучит классически и просто, не так ли? Ну, вы должны обработать $$$q$$$ запросов следующего формата:</p><ul> <li> $$$1$$$ $$$v_1$$$ $$$v_2$$$ — добавить новое ребро, соединяющее вершину $$$v_1$$$ первой доли с вершиной $$$v_2$$$ второй доли. Это ребро получает новый индекс следующим образом: первое добавленное ребро получает индекс $$$m + 1$$$, второе — $$$m + 2$$$ и так далее. После добавления ребра вы должны вывести <span class="tex-font-style-it">хэш</span> текущей оптимальной раскраски (если существует несколько оптимальных раскрасок, выведите <span class="tex-font-style-it">хэш</span> любой из них). <span class="tex-font-style-bf">На самом деле этот хэш не будет проверен, вы можете вывести любое число в качестве ответа на этот запрос, но вас могут попросить предоставить раскраску с этим хэшем</span>; </li><li> $$$2$$$ — выведите оптимальную раскраску графа с тем же <span class="tex-font-style-it">хэшем</span>, который вы вывели при обработке предыдущего запроса. Запрос этого типа будет задан только после запроса типа $$$1$$$, и будет не более $$$10$$$ запросов этого типа. Если существует несколько оптимальных раскрасок, соответствующих этому <span class="tex-font-style-it">хэшу</span>, выведите любую из них. </li></ul><p>Обратите внимание, что если ребро было красным или синим в какой-то раскраске, оно может изменить свой цвет в следующих раскрасках.</p><p><span class="tex-font-style-it">Хэш</span> раскраски вычисляется следующим образом: пусть $$$R$$$ — множество индексов красных ребер, тогда <span class="tex-font-style-it">хэш</span> равен $$$(\sum \limits_{i \in R} 2^i) \bmod 998244353$$$.</p><p>Обратите внимание, что вы должны решить эту задачу в режиме <span class="tex-font-style-tt">online</span>. Это означает, что вы не можете считать все входные данные сразу. Вы можете считать каждый запрос только после вывода ответа на последний запрос. Используйте функции <span class="tex-font-style-tt">fflush</span> в <span class="tex-font-style-tt">C++</span> и <span class="tex-font-style-tt">BufferedWriter.flush</span> в <span class="tex-font-style-tt">Java</span> после каждого вывода в вашей программе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n_1$$$, $$$n_2$$$ и $$$m$$$ ($$$1 \le n_1, n_2, m \le 2 \cdot 10^5$$$).</p><p>Затем следуют $$$m$$$ строк, в $$$i$$$-й строке записаны два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i \le n_1$$$; $$$1 \le y_i \le n_2$$$), означающие, что $$$i$$$-е ребро соединяет вершину $$$x_i$$$ из первой доли и вершину $$$y_i$$$ из второй доли.</p><p>В следующей строке записано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество запросов, которые требуется обработать.</p><p>В следующих $$$q$$$ строках содержатся запросы в формате, описанном в условии.</p><p>Дополнительные ограничения на входные данные: </p><ul> <li> в любой момент времени в графе нет кратных ребер; </li><li> все запросы типа $$$2$$$ задаются только если предыдущий запрос был типа $$$1$$$; </li><li> всего не более $$$10$$$ запросов типа $$$2$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Чтобы ответить на запрос типа $$$1$$$ выведите одно целое число — <span class="tex-font-style-it">хэш</span> оптимальной раскраски.</p><p>Чтобы ответить на запрос типа $$$2$$$ выведите одну строку. Она должна начинаться с целого числа $$$k$$$ — количество красных ребер. Затем должны идти $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисел — номера <span class="tex-font-style-bf">красных</span> ребер в вашей раскраске в любом порядке. Каждый номер должен соответствовать существующему ребру, а <span class="tex-font-style-it">хэш</span> раскраски, которую вы вывели, должен быть равен <span class="tex-font-style-it">хэшу</span>, который вы вывели в ответ на прошлый запрос.</p><p>Если существует несколько ответов на запрос, то выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 2 1 2 3 4 10 1 1 3 1 2 3 2 1 3 3 2 1 2 4 2 1 2 1 1 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 8 1 3 40 2 3 5 104 3 5 6 3 104 360 4 5 6 3 8 </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="ffc0e03f7dbd208c72e72d02f165140f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cb7745c9f9f9d8c90b5c8452dc924856b3180f42"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ffc0e03f7dbd208c72e72d02f165140f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1499%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='ffc0e03f7dbd208c72e72d02f165140f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1499">Educational Codeforces Round 106 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='ffc0e03f7dbd208c72e72d02f165140f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1499/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ffc0e03f7dbd208c72e72d02f165140f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="928255"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ffc0e03f7dbd208c72e72d02f165140f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="928255"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88744" title="Educational Codeforces Round 106 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13302:13303" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88812" title="Разбор Educational Codeforces Round 106" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13321:13322" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1499">Задачи</a></li> <li><a href="/contest/1499/submit">Отослать</a></li> <li><a href="/contest/1499/my">Мои посылки</a></li> <li><a href="/contest/1499/status">Статус</a></li> <li><a href="/contest/1499/hacks">Взломы</a></li> <li><a href="/contest/1499/standings">Положение</a></li> <li><a href="/contest/1499/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_dbebc1065e319f5dfdbeeda8021f46c120608d35"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Раскраска графа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>Вам дан двудольный граф, состоящий из $$$n_1$$$ вершин в первой доле и $$$n_2$$$ вершин во второй доле и $$$m$$$ ребер, пронумерованных от $$$1$$$ до $$$m$$$. Вы должны раскрасить каждые ребро в один из двух цветов, красный и синий. Необходимо минимизировать следующее значение: $$$\sum \limits_{v \in V} |r(v) - b(v)|$$$, где $$$V$$$ — множество вершин графа, $$$r(v)$$$ — число красных ребер, инцидентных $$$v$$$, и $$$b(v)$$$ — число синих ребер, инцидентных $$$v$$$.</p><p>Звучит классически и просто, не так ли? Ну, вы должны обработать $$$q$$$ запросов следующего формата:</p><ul> <li> $$$1$$$ $$$v_1$$$ $$$v_2$$$ — добавить новое ребро, соединяющее вершину $$$v_1$$$ первой доли с вершиной $$$v_2$$$ второй доли. Это ребро получает новый индекс следующим образом: первое добавленное ребро получает индекс $$$m + 1$$$, второе — $$$m + 2$$$ и так далее. После добавления ребра вы должны вывести <span class="tex-font-style-it">хэш</span> текущей оптимальной раскраски (если существует несколько оптимальных раскрасок, выведите <span class="tex-font-style-it">хэш</span> любой из них). <span class="tex-font-style-bf">На самом деле этот хэш не будет проверен, вы можете вывести любое число в качестве ответа на этот запрос, но вас могут попросить предоставить раскраску с этим хэшем</span>; </li><li> $$$2$$$ — выведите оптимальную раскраску графа с тем же <span class="tex-font-style-it">хэшем</span>, который вы вывели при обработке предыдущего запроса. Запрос этого типа будет задан только после запроса типа $$$1$$$, и будет не более $$$10$$$ запросов этого типа. Если существует несколько оптимальных раскрасок, соответствующих этому <span class="tex-font-style-it">хэшу</span>, выведите любую из них. </li></ul><p>Обратите внимание, что если ребро было красным или синим в какой-то раскраске, оно может изменить свой цвет в следующих раскрасках.</p><p><span class="tex-font-style-it">Хэш</span> раскраски вычисляется следующим образом: пусть $$$R$$$ — множество индексов красных ребер, тогда <span class="tex-font-style-it">хэш</span> равен $$$(\sum \limits_{i \in R} 2^i) \bmod 998244353$$$.</p><p>Обратите внимание, что вы должны решить эту задачу в режиме <span class="tex-font-style-tt">online</span>. Это означает, что вы не можете считать все входные данные сразу. Вы можете считать каждый запрос только после вывода ответа на последний запрос. Используйте функции <span class="tex-font-style-tt">fflush</span> в <span class="tex-font-style-tt">C++</span> и <span class="tex-font-style-tt">BufferedWriter.flush</span> в <span class="tex-font-style-tt">Java</span> после каждого вывода в вашей программе.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n_1$$$, $$$n_2$$$ и $$$m$$$ ($$$1 \le n_1, n_2, m \le 2 \cdot 10^5$$$).</p><p>Затем следуют $$$m$$$ строк, в $$$i$$$-й строке записаны два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i \le n_1$$$; $$$1 \le y_i \le n_2$$$), означающие, что $$$i$$$-е ребро соединяет вершину $$$x_i$$$ из первой доли и вершину $$$y_i$$$ из второй доли.</p><p>В следующей строке записано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество запросов, которые требуется обработать.</p><p>В следующих $$$q$$$ строках содержатся запросы в формате, описанном в условии.</p><p>Дополнительные ограничения на входные данные: </p><ul> <li> в любой момент времени в графе нет кратных ребер; </li><li> все запросы типа $$$2$$$ задаются только если предыдущий запрос был типа $$$1$$$; </li><li> всего не более $$$10$$$ запросов типа $$$2$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Чтобы ответить на запрос типа $$$1$$$ выведите одно целое число — <span class="tex-font-style-it">хэш</span> оптимальной раскраски.</p><p>Чтобы ответить на запрос типа $$$2$$$ выведите одну строку. Она должна начинаться с целого числа $$$k$$$ — количество красных ребер. Затем должны идти $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисел — номера <span class="tex-font-style-bf">красных</span> ребер в вашей раскраске в любом порядке. Каждый номер должен соответствовать существующему ребру, а <span class="tex-font-style-it">хэш</span> раскраски, которую вы вывели, должен быть равен <span class="tex-font-style-it">хэшу</span>, который вы вывели в ответ на прошлый запрос.</p><p>Если существует несколько ответов на запрос, то выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 2 1 2 3 4 10 1 1 3 1 2 3 2 1 3 3 2 1 2 4 2 1 2 1 1 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 8 1 3 40 2 3 5 104 3 5 6 3 104 360 4 5 6 3 8 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:34</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be2859e40058',t:'MTY5NjY2NzAxNC42MTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3100"]
1500A
1500
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> индекса $$$x, y, z, w$$$ таких, что $$$a_x + a_y = a_z + a_w$$$.</p><p>Занявшись этим делом, Настя не заметила, как прошло время, и её поезд уже пришел на станцию назначения. Она не успела закончить проверку, но всё ещё хочет узнать истину. Сможете ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — количество чисел в массиве.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$).</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>Если они существуют, далее выведите сами индексы $$$x$$$, $$$y$$$, $$$z$$$ и $$$w$$$ ($$$1 \le x, y, z, w \le n$$$).</p><p>Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 5 2 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 1 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 1 9 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Обратите внимание, что ответ <span class="tex-font-style-tt">2 3 4 6</span> также подходит.</p><p>Во втором примере нельзя выбрать четыре таких индекса. Ответ <span class="tex-font-style-tt">1 2 2 3</span> не подходит, потому что в нем не все индексы различны, хоть и $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_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="c67c24f7a055ea54622ddf7059cecbd7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="b55f3f064ce8fb3a4a8bea6893a891303aa87525"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c67c24f7a055ea54622ddf7059cecbd7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1500%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='c67c24f7a055ea54622ddf7059cecbd7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1500">Codeforces Round 707 (Div. 1, по задачам Открытой олимпиады школьников по программированию)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c67c24f7a055ea54622ddf7059cecbd7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1500/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='c67c24f7a055ea54622ddf7059cecbd7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922992"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c67c24f7a055ea54622ddf7059cecbd7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922992"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13262:13263" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13276" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1500">Задачи</a></li> <li><a href="/contest/1500/submit">Отослать</a></li> <li><a href="/contest/1500/my">Мои посылки</a></li> <li><a href="/contest/1500/status">Статус</a></li> <li><a href="/contest/1500/hacks">Взломы</a></li> <li><a href="/contest/1500/room/1">Комната</a></li> <li><a href="/contest/1500/standings">Положение</a></li> <li><a href="/contest/1500/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d82ad0ffdd278eec399fa5b0b0df86d76a431805"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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> индекса $$$x, y, z, w$$$ таких, что $$$a_x + a_y = a_z + a_w$$$.</p><p>Занявшись этим делом, Настя не заметила, как прошло время, и её поезд уже пришел на станцию назначения. Она не успела закончить проверку, но всё ещё хочет узнать истину. Сможете ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — количество чисел в массиве.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$).</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>Если они существуют, далее выведите сами индексы $$$x$$$, $$$y$$$, $$$z$$$ и $$$w$$$ ($$$1 \le x, y, z, w \le n$$$).</p><p>Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 5 2 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 1 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 1 9 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Обратите внимание, что ответ <span class="tex-font-style-tt">2 3 4 6</span> также подходит.</p><p>Во втором примере нельзя выбрать четыре таких индекса. Ответ <span class="tex-font-style-tt">1 2 2 3</span> не подходит, потому что в нем не все индексы различны, хоть и $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3$$$</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:36</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be314e969d3d',t:'MTY5NjY2NzAxNi4yMjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\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", "\u0445\u044d\u0448\u0438", "*1800"]
1500B
1500
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><p>Из-за того, что люстры разные, в некоторые дни они будут светить одинаково, а в некоторые — по-разному. Естественно, это не солидно, и вообще раздражает Васю, так что когда в $$$k$$$-й раз наступит событие «сегодня люстры светят разными цветами», Вася очень разозлится и кого-то уволит (вероятно, сотрудника, купившего люстры). Ваша задача – понять, на какой день, начиная со дня установки люстр, это случится. Считайте, что Вася очень любит работать, поэтому работает каждый день, без праздников и выходных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — количество цветов в первой люстре, количество цветов во второй люстре и сколько раз люстры должны гореть разным цветом, чтобы Вася очень разозлился.</p><p>Во второй строке даны $$$n$$$ <span class="tex-font-style-bf">различных</span> чисел $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для первой люстры.</p><p>В третьей строке даны $$$m$$$ <span class="tex-font-style-bf">различных</span> чисел $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для второй люстры.</p><p>В $$$i$$$-й день первая люстра светит цветом $$$a_x$$$, где $$$x = ((i - 1) \mod n) + 1)$$$, а вторая цветом $$$b_y$$$, где $$$y = ((i - 1) \mod m) + 1)$$$.</p><p>Гарантируется, что последовательность $$$a$$$ не совпадает тождественно с последовательностью $$$b$$$, а значит лампы будут периодически раздражать Васю.</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 4 4 2 3 1 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 8 41 1 3 2 1 6 4 3 5 7 2 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 47 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 31 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 62 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте из условия люстры будут гореть разными цветами в дни $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$. Соответственно ответом является $$$5$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="df2a5886a1b1108efc5c5bcc985ac45c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="b55f3f064ce8fb3a4a8bea6893a891303aa87525"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='df2a5886a1b1108efc5c5bcc985ac45c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1500%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='df2a5886a1b1108efc5c5bcc985ac45c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1500">Codeforces Round 707 (Div. 1, по задачам Открытой олимпиады школьников по программированию)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='df2a5886a1b1108efc5c5bcc985ac45c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1500/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Китайская теорема об остатках, алгоритм Гарнера"> китайская теорема об остатках </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='df2a5886a1b1108efc5c5bcc985ac45c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922993"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='df2a5886a1b1108efc5c5bcc985ac45c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922993"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13262:13263" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13276" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1500">Задачи</a></li> <li><a href="/contest/1500/submit">Отослать</a></li> <li><a href="/contest/1500/my">Мои посылки</a></li> <li><a href="/contest/1500/status">Статус</a></li> <li><a href="/contest/1500/hacks">Взломы</a></li> <li><a href="/contest/1500/room/1">Комната</a></li> <li><a href="/contest/1500/standings">Положение</a></li> <li><a href="/contest/1500/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e4b60d078ecb75e99f6b3ea8b92f2c52edf05dbd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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><p>Из-за того, что люстры разные, в некоторые дни они будут светить одинаково, а в некоторые — по-разному. Естественно, это не солидно, и вообще раздражает Васю, так что когда в $$$k$$$-й раз наступит событие «сегодня люстры светят разными цветами», Вася очень разозлится и кого-то уволит (вероятно, сотрудника, купившего люстры). Ваша задача – понять, на какой день, начиная со дня установки люстр, это случится. Считайте, что Вася очень любит работать, поэтому работает каждый день, без праздников и выходных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — количество цветов в первой люстре, количество цветов во второй люстре и сколько раз люстры должны гореть разным цветом, чтобы Вася очень разозлился.</p><p>Во второй строке даны $$$n$$$ <span class="tex-font-style-bf">различных</span> чисел $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для первой люстры.</p><p>В третьей строке даны $$$m$$$ <span class="tex-font-style-bf">различных</span> чисел $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для второй люстры.</p><p>В $$$i$$$-й день первая люстра светит цветом $$$a_x$$$, где $$$x = ((i - 1) \mod n) + 1)$$$, а вторая цветом $$$b_y$$$, где $$$y = ((i - 1) \mod m) + 1)$$$.</p><p>Гарантируется, что последовательность $$$a$$$ не совпадает тождественно с последовательностью $$$b$$$, а значит лампы будут периодически раздражать Васю.</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 4 4 2 3 1 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 8 41 1 3 2 1 6 4 3 5 7 2 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 47 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 31 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 62 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте из условия люстры будут гореть разными цветами в дни $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$. Соответственно ответом является $$$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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:37</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be3b2a389da4',t:'MTY5NjY2NzAxNy42NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0438\u0442\u0430\u0439\u0441\u043a\u0430\u044f \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u043e\u0431 \u043e\u0441\u0442\u0430\u0442\u043a\u0430\u0445, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0413\u0430\u0440\u043d\u0435\u0440\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043a\u0438\u0442\u0430\u0439\u0441\u043a\u0430\u044f \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u043e\u0431 \u043e\u0441\u0442\u0430\u0442\u043a\u0430\u0445", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2200"]
1500C
1500
C
ru
C. Сортировка матрицы
<div class="problem-statement"><div class="header"><div class="title">C. Сортировка матрицы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Даны две таблицы $$$A$$$ и $$$B$$$ размера $$$n \times m$$$. </p><p>Назовём <span class="tex-font-style-it">сортировкой по столбцу</span> следующее действие: выбирается столбец, и все строки упорядочиваются по значению в этом столбце, от строк, содержащих меньшие значения, к строкам с большими. В случае, если две строки имеют одинаковое значение в этом столбце, их порядок не меняется (такие сортировки называются <span class="tex-font-style-it">стабильными</span>).</p><p>Подобное поведение сортировки по столбцу можно найти практически в любом офисном приложении для работы с таблицами. Петя работает в одном из таких приложений, и у него открыта таблица $$$A$$$. Он хочет проделать ноль или более операций сортировки по столбцу, чтобы получить таблицу $$$B$$$.</p><p>Определите, может ли он это сделать, и если может, предложите ему алгоритм действий — последовательность столбцов, по которым нужно применить сортировку по столбцу. Обратите внимание, что <span class="tex-font-style-bf">не требуется</span> минимизировать число действий.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 1500$$$) — размеры таблицы.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$a_{i,j}$$$ ($$$1 \le a_{i, j} \le n$$$) — элементы таблицы $$$A$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$b_{i, j}$$$ ($$$1 \le b_{i, j} \le n$$$) — элементы таблицы $$$B$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если превратить таблицу $$$A$$$ в таблицу $$$B$$$ невозможно, выведите $$$-1$$$.</p><p>В противном случае выведите $$$k$$$ ($$$0 \le k \le 5000$$$) — количество сортировок, которые нужно сделать.</p><p>Затем выведите $$$k$$$ целых чисел $$$c_1, \ldots, c_k$$$ ($$$1 \le c_i \le m$$$) — номера столбцов, по которым нужно сделать сортировку.</p><p>Можно доказать, что если Петя может осуществить желаемое, то $$$5000$$$ действий ему хватит.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 2 1 2 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 1 2 1 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 2 1 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим второй пример. После сортировки по первому столбцу таблица имеет вид</p><p>$$$$$$\begin{matrix} 1&amp;3&amp;3\\ 1&amp;1&amp;2\\ 2&amp;3&amp;2. \end{matrix}$$$$$$</p><p>После того, как мы отсортируем таблицу по второму столбцу, она станет</p><p>$$$$$$\begin{matrix} 1&amp;1&amp;2\\ 1&amp;3&amp;3\\ 2&amp;3&amp;2, \end{matrix}$$$$$$</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="b22af2663fe023b132060607464a6b42"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="b55f3f064ce8fb3a4a8bea6893a891303aa87525"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b22af2663fe023b132060607464a6b42'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1500%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='b22af2663fe023b132060607464a6b42'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1500">Codeforces Round 707 (Div. 1, по задачам Открытой олимпиады школьников по программированию)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b22af2663fe023b132060607464a6b42'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1500/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='b22af2663fe023b132060607464a6b42'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922994"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b22af2663fe023b132060607464a6b42'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922994"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13262:13263" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13276" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1500">Задачи</a></li> <li><a href="/contest/1500/submit">Отослать</a></li> <li><a href="/contest/1500/my">Мои посылки</a></li> <li><a href="/contest/1500/status">Статус</a></li> <li><a href="/contest/1500/hacks">Взломы</a></li> <li><a href="/contest/1500/room/1">Комната</a></li> <li><a href="/contest/1500/standings">Положение</a></li> <li><a href="/contest/1500/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_16cb93524fbce0e13c6b00af49c5d39ee9a5454d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Сортировка матрицы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Даны две таблицы $$$A$$$ и $$$B$$$ размера $$$n \times m$$$. </p><p>Назовём <span class="tex-font-style-it">сортировкой по столбцу</span> следующее действие: выбирается столбец, и все строки упорядочиваются по значению в этом столбце, от строк, содержащих меньшие значения, к строкам с большими. В случае, если две строки имеют одинаковое значение в этом столбце, их порядок не меняется (такие сортировки называются <span class="tex-font-style-it">стабильными</span>).</p><p>Подобное поведение сортировки по столбцу можно найти практически в любом офисном приложении для работы с таблицами. Петя работает в одном из таких приложений, и у него открыта таблица $$$A$$$. Он хочет проделать ноль или более операций сортировки по столбцу, чтобы получить таблицу $$$B$$$.</p><p>Определите, может ли он это сделать, и если может, предложите ему алгоритм действий — последовательность столбцов, по которым нужно применить сортировку по столбцу. Обратите внимание, что <span class="tex-font-style-bf">не требуется</span> минимизировать число действий.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 1500$$$) — размеры таблицы.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$a_{i,j}$$$ ($$$1 \le a_{i, j} \le n$$$) — элементы таблицы $$$A$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$b_{i, j}$$$ ($$$1 \le b_{i, j} \le n$$$) — элементы таблицы $$$B$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если превратить таблицу $$$A$$$ в таблицу $$$B$$$ невозможно, выведите $$$-1$$$.</p><p>В противном случае выведите $$$k$$$ ($$$0 \le k \le 5000$$$) — количество сортировок, которые нужно сделать.</p><p>Затем выведите $$$k$$$ целых чисел $$$c_1, \ldots, c_k$$$ ($$$1 \le c_i \le m$$$) — номера столбцов, по которым нужно сделать сортировку.</p><p>Можно доказать, что если Петя может осуществить желаемое, то $$$5000$$$ действий ему хватит.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 2 1 2 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 1 2 1 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 2 1 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим второй пример. После сортировки по первому столбцу таблица имеет вид</p><p>$$$$$$\begin{matrix} 1&amp;3&amp;3\\ 1&amp;1&amp;2\\ 2&amp;3&amp;2. \end{matrix}$$$$$$</p><p>После того, как мы отсортируем таблицу по второму столбцу, она станет</p><p>$$$$$$\begin{matrix} 1&amp;1&amp;2\\ 1&amp;3&amp;3\\ 2&amp;3&amp;2, \end{matrix}$$$$$$</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:39</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be443c027903',t:'MTY5NjY2NzAxOS4xMzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\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"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2600"]
1500D
1500
D
ru
D. Плитка для ванной
<div class="problem-statement"><div class="header"><div class="title">D. Плитка для ванной</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>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>У Кости очень много дел: ремонт в самом разгаре! Надо клеить обои, собирать мебель и постоянно вывозить мусор.</p><p>Сегодня Костя хочет купить плитку для ванной. Он пришел в магазин и оказался перед большим квадратным стендом с плиткой. Стенд представляет из себя квадрат из $$$n \times n$$$ клеток, каждая клетка которого — маленький кусочек плитки цвета $$$c_{i,\,j}$$$. Магазин продает кусочки плитки пакетами, а именно, купить можно только подквадрат исходного квадрата.</p><p>Подквадратом называется любой квадратный фрагмент стенда, то есть любое множество $$$S(i_0, j_0, k) = \{c_{i,\,j}\ |\ i_0 \le i &lt; i_0 + k, j_0 \le j &lt; j_0 + k\}$$$ при $$$1 \le i_0, j_0 \le n - k + 1$$$.</p><p>Костя еще не знает, сколько кусочков плитки он хочет купить, и, соответственно, рассматривает подквадраты всех возможных размеров. При этом он точно не хочет слишком разноцветную плитку в ванной, что позволяет ему сузить выбор. Помогите Косте для каждого $$$k \le n$$$ определить количество различных подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов плитки. Подквадраты считаются различными, если их расположение на стенде не совпадает.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых положительных числа $$$n$$$, $$$q$$$ ($$$1 \le n \le 1500$$$, $$$1 \le q \le 10$$$) — размер стенда с плитками и ограничение на количество различных цветов в пакете.</p><p>В следующих $$$n$$$ строках находятся по $$$n$$$ целых положительных чисел $$$c_{i,\,j}$$$ ($$$1 \le c_{i,\,j} \le n^2$$$): $$$j$$$-е число в $$$i$$$-й строке соответствует цвету плитки в клетке $$$(i,\,j)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$ выведите в отдельной строке по одному целому числу — количество подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 9 4 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все цвета квадратиков плитки различные. Поскольку Костя не хочет, чтобы в купленном квадрате было больше $$$4$$$ цветов, он может купить себе любой подквадрат размера $$$1 \times 1$$$ или $$$2 \times 2$$$, но при этом не сможет купить квадрат размера $$$3 \times 3$$$.</p><p>Во втором примере есть повторяющиеся цвета. А именно, за счет ограничения $$$q = 8$$$ Костя может купить любой подквадрат $$$1 \times 1$$$ и $$$2 \times 2$$$, а также любой подквадрат $$$3 \times 3$$$, ведь в каждом таком подквадрате всего $$$7$$$ цветов. Весь стенд размера $$$4 \times 4$$$ Костя купить не сможет, потому что там будет $$$9$$$ цветов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2471b28100019dc4b2b9f489cdd54b02"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="b55f3f064ce8fb3a4a8bea6893a891303aa87525"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2471b28100019dc4b2b9f489cdd54b02'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1500%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='2471b28100019dc4b2b9f489cdd54b02'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1500">Codeforces Round 707 (Div. 1, по задачам Открытой олимпиады школьников по программированию)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2471b28100019dc4b2b9f489cdd54b02'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1500/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='2471b28100019dc4b2b9f489cdd54b02'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922995"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2471b28100019dc4b2b9f489cdd54b02'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922995"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13262:13263" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13276" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1500">Задачи</a></li> <li><a href="/contest/1500/submit">Отослать</a></li> <li><a href="/contest/1500/my">Мои посылки</a></li> <li><a href="/contest/1500/status">Статус</a></li> <li><a href="/contest/1500/hacks">Взломы</a></li> <li><a href="/contest/1500/room/1">Комната</a></li> <li><a href="/contest/1500/standings">Положение</a></li> <li><a href="/contest/1500/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_caf6f39f60a28366b9234ab6edccf9010bd29c43"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>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>У Кости очень много дел: ремонт в самом разгаре! Надо клеить обои, собирать мебель и постоянно вывозить мусор.</p><p>Сегодня Костя хочет купить плитку для ванной. Он пришел в магазин и оказался перед большим квадратным стендом с плиткой. Стенд представляет из себя квадрат из $$$n \times n$$$ клеток, каждая клетка которого — маленький кусочек плитки цвета $$$c_{i,\,j}$$$. Магазин продает кусочки плитки пакетами, а именно, купить можно только подквадрат исходного квадрата.</p><p>Подквадратом называется любой квадратный фрагмент стенда, то есть любое множество $$$S(i_0, j_0, k) = \{c_{i,\,j}\ |\ i_0 \le i &lt; i_0 + k, j_0 \le j &lt; j_0 + k\}$$$ при $$$1 \le i_0, j_0 \le n - k + 1$$$.</p><p>Костя еще не знает, сколько кусочков плитки он хочет купить, и, соответственно, рассматривает подквадраты всех возможных размеров. При этом он точно не хочет слишком разноцветную плитку в ванной, что позволяет ему сузить выбор. Помогите Косте для каждого $$$k \le n$$$ определить количество различных подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов плитки. Подквадраты считаются различными, если их расположение на стенде не совпадает.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых положительных числа $$$n$$$, $$$q$$$ ($$$1 \le n \le 1500$$$, $$$1 \le q \le 10$$$) — размер стенда с плитками и ограничение на количество различных цветов в пакете.</p><p>В следующих $$$n$$$ строках находятся по $$$n$$$ целых положительных чисел $$$c_{i,\,j}$$$ ($$$1 \le c_{i,\,j} \le n^2$$$): $$$j$$$-е число в $$$i$$$-й строке соответствует цвету плитки в клетке $$$(i,\,j)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$ выведите в отдельной строке по одному целому числу — количество подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 9 4 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все цвета квадратиков плитки различные. Поскольку Костя не хочет, чтобы в купленном квадрате было больше $$$4$$$ цветов, он может купить себе любой подквадрат размера $$$1 \times 1$$$ или $$$2 \times 2$$$, но при этом не сможет купить квадрат размера $$$3 \times 3$$$.</p><p>Во втором примере есть повторяющиеся цвета. А именно, за счет ограничения $$$q = 8$$$ Костя может купить любой подквадрат $$$1 \times 1$$$ и $$$2 \times 2$$$, а также любой подквадрат $$$3 \times 3$$$, ведь в каждом таком подквадрате всего $$$7$$$ цветов. Весь стенд размера $$$4 \times 4$$$ Костя купить не сможет, потому что там будет $$$9$$$ цветов.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:40</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be4d7bb50c48',t:'MTY5NjY2NzAyMC41MDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2900"]
1500E
1500
E
ru
E. Фокус с подмножествами
<div class="problem-statement"><div class="header"><div class="title">E. Фокус с подмножествами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ваня придумал интересный фокус с множеством целых чисел.</p><p>Пусть у фокусника есть множество положительных целых чисел $$$S$$$. Он называет некоторое положительное целое число $$$x$$$. Зритель должен выбрать, не показывая фокуснику, некоторое подмножество $$$S$$$ (возможно пустое). После этого зритель называет фокуснику размер выбранного подмножества. Фокус заключается в том, что после этого фокусник отгадывает: верно ли, что сумма элементов выбранного подмножества не превосходит $$$x$$$. Для пустого подмножества сумма предполагается равной $$$0$$$.</p><p>Ване очень понравился этот фокус, поэтому он начал готовиться к тому, чтобы показать его публике. Для этого он приготовил некоторое множество <span class="tex-font-style-bf">различных</span> положительных целых чисел $$$S$$$. Конечно, Ваня хочет, чтобы фокус обязательно получился. Он называет положительное целое число $$$x$$$ <span class="tex-font-style-it">неудачным</span>, если не может быть точно уверен, что фокус пройдет удачно для любого подмножества, которое выберет зритель.</p><p>Чтобы оценить, насколько хорошее множество $$$S$$$ он выбрал, он хочет посчитать количество неудачных положительных целых чисел для него.</p><p>Также Ваня планирует протестировать различные множества $$$S$$$. Поэтому он просит вас написать программу, которая найдет количество неудачных положительных целых чисел для изначального множества $$$S$$$ и для множества $$$S$$$ после каждого изменения. Ваня сделает $$$q$$$ изменений своего множества, каждое изменение будет одного из двух видов:</p><ul> <li> Добавить новое число $$$a$$$ в множество $$$S$$$. </li><li> Удалить некоторое число $$$a$$$ из множества $$$S$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$, $$$q$$$ ($$$1 \leq n, q \leq 200\,000$$$) — размер изначального множества $$$S$$$ и количество изменений.</p><p>В следующей строке находятся $$$n$$$ <span class="tex-font-style-bf">различных</span> целых чисел $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \leq s_i \leq 10^{13}$$$) — элементы изначального множества $$$S$$$.</p><p>В каждой из следующих $$$q$$$ строк находятся два целых числа $$$t_i$$$, $$$a_i$$$ ($$$1 \leq t_i \leq 2$$$, $$$1 \leq a_i \leq 10^{13}$$$), описывающих очередное изменение. </p><ul> <li> Если $$$t_i = 1$$$, то это операция добавления нового числа $$$a_i$$$ в множество $$$S$$$. Гарантируется, что этого числа не было в множестве $$$S$$$ до выполнения операции. </li><li> Если $$$t_i = 2$$$, то это операция удаления числа $$$a_i$$$ из множества $$$S$$$. Гарантируется, что это число было в множестве $$$S$$$ до выполнения операции. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ строку.</p><p>В первой строке выведите количество неудачных положительных целых чисел для изначального множества $$$S$$$. В следующих $$$q$$$ строках выведите количество неудачных положительных чисел для множества $$$S$$$ после каждого изменения.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 6 12 19 13 8 2 10 3 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте изначальное $$$S = \{1, 2, 3\}$$$. Для этого множества фокус может не получиться при $$$x \in \{1, 2, 3, 4\}$$$. Например, если $$$x = 4$$$, то зритель может загадать подмножество $$$\{1, 2\}$$$, сумма элементов которого равна $$$3 \leq x$$$, а может загадать подмножество $$$\{2, 3\}$$$, сумма элементов которого равна $$$5 &gt; x$$$. Однако в обоих случаях зритель назовет фокуснику размер подмножества $$$2$$$, поэтому он не сможет точно сделать правильный ответ. При этом поскольку подмножество размера $$$3$$$ единственно, а сумма в любом подмножестве меньшего размера не превосходит $$$5$$$, все $$$x \ge 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="8781f9cb0671b16cc8499b0ee55cd981"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="b55f3f064ce8fb3a4a8bea6893a891303aa87525"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8781f9cb0671b16cc8499b0ee55cd981'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1500%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='8781f9cb0671b16cc8499b0ee55cd981'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1500">Codeforces Round 707 (Div. 1, по задачам Открытой олимпиады школьников по программированию)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8781f9cb0671b16cc8499b0ee55cd981'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1500/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='8781f9cb0671b16cc8499b0ee55cd981'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922996"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8781f9cb0671b16cc8499b0ee55cd981'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922996"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13262:13263" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13276" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1500">Задачи</a></li> <li><a href="/contest/1500/submit">Отослать</a></li> <li><a href="/contest/1500/my">Мои посылки</a></li> <li><a href="/contest/1500/status">Статус</a></li> <li><a href="/contest/1500/hacks">Взломы</a></li> <li><a href="/contest/1500/room/1">Комната</a></li> <li><a href="/contest/1500/standings">Положение</a></li> <li><a href="/contest/1500/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_345e95c670a8ad6a607f900d53eda262ff529728"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Фокус с подмножествами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ваня придумал интересный фокус с множеством целых чисел.</p><p>Пусть у фокусника есть множество положительных целых чисел $$$S$$$. Он называет некоторое положительное целое число $$$x$$$. Зритель должен выбрать, не показывая фокуснику, некоторое подмножество $$$S$$$ (возможно пустое). После этого зритель называет фокуснику размер выбранного подмножества. Фокус заключается в том, что после этого фокусник отгадывает: верно ли, что сумма элементов выбранного подмножества не превосходит $$$x$$$. Для пустого подмножества сумма предполагается равной $$$0$$$.</p><p>Ване очень понравился этот фокус, поэтому он начал готовиться к тому, чтобы показать его публике. Для этого он приготовил некоторое множество <span class="tex-font-style-bf">различных</span> положительных целых чисел $$$S$$$. Конечно, Ваня хочет, чтобы фокус обязательно получился. Он называет положительное целое число $$$x$$$ <span class="tex-font-style-it">неудачным</span>, если не может быть точно уверен, что фокус пройдет удачно для любого подмножества, которое выберет зритель.</p><p>Чтобы оценить, насколько хорошее множество $$$S$$$ он выбрал, он хочет посчитать количество неудачных положительных целых чисел для него.</p><p>Также Ваня планирует протестировать различные множества $$$S$$$. Поэтому он просит вас написать программу, которая найдет количество неудачных положительных целых чисел для изначального множества $$$S$$$ и для множества $$$S$$$ после каждого изменения. Ваня сделает $$$q$$$ изменений своего множества, каждое изменение будет одного из двух видов:</p><ul> <li> Добавить новое число $$$a$$$ в множество $$$S$$$. </li><li> Удалить некоторое число $$$a$$$ из множества $$$S$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$, $$$q$$$ ($$$1 \leq n, q \leq 200\,000$$$) — размер изначального множества $$$S$$$ и количество изменений.</p><p>В следующей строке находятся $$$n$$$ <span class="tex-font-style-bf">различных</span> целых чисел $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \leq s_i \leq 10^{13}$$$) — элементы изначального множества $$$S$$$.</p><p>В каждой из следующих $$$q$$$ строк находятся два целых числа $$$t_i$$$, $$$a_i$$$ ($$$1 \leq t_i \leq 2$$$, $$$1 \leq a_i \leq 10^{13}$$$), описывающих очередное изменение. </p><ul> <li> Если $$$t_i = 1$$$, то это операция добавления нового числа $$$a_i$$$ в множество $$$S$$$. Гарантируется, что этого числа не было в множестве $$$S$$$ до выполнения операции. </li><li> Если $$$t_i = 2$$$, то это операция удаления числа $$$a_i$$$ из множества $$$S$$$. Гарантируется, что это число было в множестве $$$S$$$ до выполнения операции. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ строку.</p><p>В первой строке выведите количество неудачных положительных целых чисел для изначального множества $$$S$$$. В следующих $$$q$$$ строках выведите количество неудачных положительных чисел для множества $$$S$$$ после каждого изменения.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 6 12 19 13 8 2 10 3 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте изначальное $$$S = \{1, 2, 3\}$$$. Для этого множества фокус может не получиться при $$$x \in \{1, 2, 3, 4\}$$$. Например, если $$$x = 4$$$, то зритель может загадать подмножество $$$\{1, 2\}$$$, сумма элементов которого равна $$$3 \leq x$$$, а может загадать подмножество $$$\{2, 3\}$$$, сумма элементов которого равна $$$5 &gt; x$$$. Однако в обоих случаях зритель назовет фокуснику размер подмножества $$$2$$$, поэтому он не сможет точно сделать правильный ответ. При этом поскольку подмножество размера $$$3$$$ единственно, а сумма в любом подмножестве меньшего размера не превосходит $$$5$$$, все $$$x \ge 5$$$ не являются неудачными.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:41</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be55dd3b9d40',t:'MTY5NjY2NzAyMS44MjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3300"]
1500F
1500
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>В доме Кроша стояло $$$n$$$ шкафов в линию, $$$i$$$-й шкаф имел высоту $$$h_i$$$. Недавно Крош переехал, но не смог перевезти с собой те самые шкафы. Ему хочется купить $$$n$$$ новых шкафов, чтобы те были как можно больше похожи на старые.</p><p>Крош не помнит конкретные высоты шкафов, но для каждой тройки подряд идущих шкафов он знает разность высот между самым высоким и самым низким из тройки. Иначе говоря, если последовательность высот шкафов была $$$h_1, h_2, \ldots, h_n$$$, то Крош помнит величины $$$w_i = \max(h_{i}, h_{i + 1}, h_{i + 2}) - \min(h_{i}, h_{i + 1}, h_{i + 2})$$$ для $$$1 \leq i \leq n - 2$$$.</p><p>В новый дом Крош хочет купить $$$n$$$ шкафов, так чтобы всё было как прежде: все значения $$$w_i$$$ должны сохраниться. Помогите Крошу понять, какие шкафы ему следует купить и в какой последовательности поставить, или определите, что он что-то перепутал, и такой последовательности шкафов не может быть.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ и $$$C$$$ ($$$3 \leq n \leq 10^6$$$, $$$0 \leq C \leq 10^{12}$$$) — количество шкафов и ограничение на $$$w_i$$$.</p><p>Вторая строка содержит $$$n - 2$$$ целых числа $$$w_1, w_2, \ldots, w_{n - 2}$$$ ($$$0 \leq w_i \leq C$$$) — высоты шкафов слева направо.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует возможности купить $$$n$$$ шкафов, удовлетворяющих условиям, в единственной строке выведите «<span class="tex-font-style-tt">No</span>».</p><p>Иначе в первой строке выведите «<span class="tex-font-style-tt">Yes</span>», после чего во второй строке выведите $$$n$$$ целых чисел $$$h'_1, h'_2, \ldots, h'_n$$$ ($$$0 \le h'_i \le 10^{18}$$$) — высоты шкафов для покупки.</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> 7 20 4 8 12 16 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 4 8 8 16 20 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 11 10 5 7 2 3 4 5 2 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 1 6 8 6 5 2 0 0 1 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 9 1 6 9 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример:</p><ul> <li> $$$w_1 = \max(4, 8, 8) - \min(4, 8, 8) = 8 - 4 = 4$$$ </li><li> $$$w_2 = \max(8, 8, 16) - \min(8, 8, 16) = 16 - 8 = 8$$$ </li><li> $$$w_3 = \max(8, 16, 20) - \min(8, 16, 20) = 20 - 8 = 12$$$ </li><li> $$$w_4 = \max(16, 20, 4) - \min(16, 20, 4) = 20 - 4 = 16$$$ </li><li> $$$w_5 = \max(20, 4, 0) - \min(20, 4, 0) = 20 - 0 = 20$$$ </li></ul><p>Также корректным был бы, например, ответ с высотами: $$$0, 1, 4, 9, 16, 25, 36$$$</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="eda0b7ca7d7f56c2c7a376ec9ec96cdf"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="b55f3f064ce8fb3a4a8bea6893a891303aa87525"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='eda0b7ca7d7f56c2c7a376ec9ec96cdf'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1500%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='eda0b7ca7d7f56c2c7a376ec9ec96cdf'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1500">Codeforces Round 707 (Div. 1, по задачам Открытой олимпиады школьников по программированию)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='eda0b7ca7d7f56c2c7a376ec9ec96cdf'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1500/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='eda0b7ca7d7f56c2c7a376ec9ec96cdf'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922997"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='eda0b7ca7d7f56c2c7a376ec9ec96cdf'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922997"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13262:13263" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13276" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1500">Задачи</a></li> <li><a href="/contest/1500/submit">Отослать</a></li> <li><a href="/contest/1500/my">Мои посылки</a></li> <li><a href="/contest/1500/status">Статус</a></li> <li><a href="/contest/1500/hacks">Взломы</a></li> <li><a href="/contest/1500/room/1">Комната</a></li> <li><a href="/contest/1500/standings">Положение</a></li> <li><a href="/contest/1500/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b4d64fe9cb17f6991f68512658ecc21ea3365675"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>В доме Кроша стояло $$$n$$$ шкафов в линию, $$$i$$$-й шкаф имел высоту $$$h_i$$$. Недавно Крош переехал, но не смог перевезти с собой те самые шкафы. Ему хочется купить $$$n$$$ новых шкафов, чтобы те были как можно больше похожи на старые.</p><p>Крош не помнит конкретные высоты шкафов, но для каждой тройки подряд идущих шкафов он знает разность высот между самым высоким и самым низким из тройки. Иначе говоря, если последовательность высот шкафов была $$$h_1, h_2, \ldots, h_n$$$, то Крош помнит величины $$$w_i = \max(h_{i}, h_{i + 1}, h_{i + 2}) - \min(h_{i}, h_{i + 1}, h_{i + 2})$$$ для $$$1 \leq i \leq n - 2$$$.</p><p>В новый дом Крош хочет купить $$$n$$$ шкафов, так чтобы всё было как прежде: все значения $$$w_i$$$ должны сохраниться. Помогите Крошу понять, какие шкафы ему следует купить и в какой последовательности поставить, или определите, что он что-то перепутал, и такой последовательности шкафов не может быть.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ и $$$C$$$ ($$$3 \leq n \leq 10^6$$$, $$$0 \leq C \leq 10^{12}$$$) — количество шкафов и ограничение на $$$w_i$$$.</p><p>Вторая строка содержит $$$n - 2$$$ целых числа $$$w_1, w_2, \ldots, w_{n - 2}$$$ ($$$0 \leq w_i \leq C$$$) — высоты шкафов слева направо.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует возможности купить $$$n$$$ шкафов, удовлетворяющих условиям, в единственной строке выведите «<span class="tex-font-style-tt">No</span>».</p><p>Иначе в первой строке выведите «<span class="tex-font-style-tt">Yes</span>», после чего во второй строке выведите $$$n$$$ целых чисел $$$h'_1, h'_2, \ldots, h'_n$$$ ($$$0 \le h'_i \le 10^{18}$$$) — высоты шкафов для покупки.</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> 7 20 4 8 12 16 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 4 8 8 16 20 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 11 10 5 7 2 3 4 5 2 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 1 6 8 6 5 2 0 0 1 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 9 1 6 9 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример:</p><ul> <li> $$$w_1 = \max(4, 8, 8) - \min(4, 8, 8) = 8 - 4 = 4$$$ </li><li> $$$w_2 = \max(8, 8, 16) - \min(8, 8, 16) = 16 - 8 = 8$$$ </li><li> $$$w_3 = \max(8, 16, 20) - \min(8, 16, 20) = 20 - 8 = 12$$$ </li><li> $$$w_4 = \max(16, 20, 4) - \min(16, 20, 4) = 20 - 4 = 16$$$ </li><li> $$$w_5 = \max(20, 4, 0) - \min(20, 4, 0) = 20 - 0 = 20$$$ </li></ul><p>Также корректным был бы, например, ответ с высотами: $$$0, 1, 4, 9, 16, 25, 36$$$</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:43</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be5dfab79d55',t:'MTY5NjY2NzAyMy4xMjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "*3500"]
1501A
1501
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>Леша садится на поезд на вокзале. Будем считать, что поезд трогается с вокзала в момент $$$0$$$. Также будем считать, что поезд пройдет через $$$n$$$ станций, пронумерованных от $$$1$$$ по $$$n$$$ в порядке маршрута поезда и Леше нужно попасть на станцию $$$n$$$.</p><p>Из маршрутного листа он узнал $$$n$$$ пар целых чисел $$$(a_i, b_i)$$$, где $$$a_i$$$ — ожидаемое время прибытия на $$$i$$$-ю станцию, а $$$b_i$$$ — ожидаемое время отбытия с нее.</p><p>Также, принимая во внимание множество факторов, Леша смог рассчитать $$$n$$$ целых чисел $$$tm_1, tm_2, \dots, tm_n$$$, где $$$tm_i$$$ — это то, на сколько больше будет ехать поезд от станции $$$i - 1$$$ до станции $$$i$$$, чем ожидалось. Формально говоря, поезд проедет от станции $$$i - 1$$$ до $$$i$$$ ровно $$$a_i - b_{i-1} + tm_i$$$ времени (при $$$i = 1$$$, за $$$b_0$$$ берется время отбытия от вокзала, равное $$$0$$$).</p><p>Поезд выезжает со станции $$$i$$$, если соблюдаются оба следующих условия: </p><ol> <li> он стоит уже хотя бы $$$\left\lceil \frac{b_i - a_i}{2} \right\rceil$$$ времени (деление с округлением вверх); </li><li> текущее время $$$\ge b_i$$$. </li></ol><p>Так как Леша потратил все силы на предсказание задержек, помогите ему посчитать время <span class="tex-font-style-bf">прибытия</span> на станцию $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество станций.</p><p>Далее заданы $$$n$$$ строк, в каждой из которых содержится два целых числа: $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i &lt; b_i \le 10^6$$$). Гарантируется, что $$$b_i &lt; a_{i+1}$$$. </p><p>В следующей строке заданы $$$n$$$ целых чисел $$$tm_1, tm_2, \dots, tm_n$$$ ($$$0 \le tm_i \le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — время прибытия Леши на последнюю станцию.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 4 10 12 0 2 5 1 4 7 8 9 10 13 15 19 20 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 32 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Леша сначала пребывает без опоздания на станцию номер $$$1$$$ в момент времени $$$a_1 = 2$$$ (так как $$$tm_1 = 0$$$). Затем отъезжает с неё в момент времени $$$b_1 = 4$$$. На станцию номер $$$2$$$ он приезжает с опозданием на $$$tm_2 = 2$$$ единицы времени, то есть в $$$12$$$.</p><p>Во втором наборе, Леша прибывает на первую станцию с опозданием в $$$tm_1 = 1$$$, то есть в момент $$$2$$$. Далее поезд должен пробыть хотя бы $$$\left\lceil \frac{b_1 - a_1}{2} \right\rceil = 2$$$ единицы времени на станции и отправится не ранее чем в момент $$$b_1 = 4$$$. Таким образом, поезд оправляется с первой станции в момент $$$4$$$.</p><p>Разбирая аналогичным образом следующие станции, можно получить, что поезд прибудет на вторую станцию в момент $$$9$$$, а покинет в $$$10$$$; на третью станцию прибудет в $$$14$$$, покинет в $$$15$$$; на четвертую: прибудет в $$$22$$$, покинет в $$$23$$$. И, наконец, прибудет на пятую в $$$32$$$.</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="0427b915d97dc55b7e09d03fd4f9a579"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="f0a97110320a5fea54a4b1c029103cf455e47f8f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0427b915d97dc55b7e09d03fd4f9a579'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1501%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='0427b915d97dc55b7e09d03fd4f9a579'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1501">Codeforces Round 707 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='0427b915d97dc55b7e09d03fd4f9a579'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1501/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='0427b915d97dc55b7e09d03fd4f9a579'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922986"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0427b915d97dc55b7e09d03fd4f9a579'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922986"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13264:13265" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13275" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1501">Задачи</a></li> <li><a href="/contest/1501/submit">Отослать</a></li> <li><a href="/contest/1501/my">Мои посылки</a></li> <li><a href="/contest/1501/status">Статус</a></li> <li><a href="/contest/1501/hacks">Взломы</a></li> <li><a href="/contest/1501/room/1">Комната</a></li> <li><a href="/contest/1501/standings">Положение</a></li> <li><a href="/contest/1501/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e07ae776e17c8eaf5e698a7396babcf45fd24f6f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Леша садится на поезд на вокзале. Будем считать, что поезд трогается с вокзала в момент $$$0$$$. Также будем считать, что поезд пройдет через $$$n$$$ станций, пронумерованных от $$$1$$$ по $$$n$$$ в порядке маршрута поезда и Леше нужно попасть на станцию $$$n$$$.</p><p>Из маршрутного листа он узнал $$$n$$$ пар целых чисел $$$(a_i, b_i)$$$, где $$$a_i$$$ — ожидаемое время прибытия на $$$i$$$-ю станцию, а $$$b_i$$$ — ожидаемое время отбытия с нее.</p><p>Также, принимая во внимание множество факторов, Леша смог рассчитать $$$n$$$ целых чисел $$$tm_1, tm_2, \dots, tm_n$$$, где $$$tm_i$$$ — это то, на сколько больше будет ехать поезд от станции $$$i - 1$$$ до станции $$$i$$$, чем ожидалось. Формально говоря, поезд проедет от станции $$$i - 1$$$ до $$$i$$$ ровно $$$a_i - b_{i-1} + tm_i$$$ времени (при $$$i = 1$$$, за $$$b_0$$$ берется время отбытия от вокзала, равное $$$0$$$).</p><p>Поезд выезжает со станции $$$i$$$, если соблюдаются оба следующих условия: </p><ol> <li> он стоит уже хотя бы $$$\left\lceil \frac{b_i - a_i}{2} \right\rceil$$$ времени (деление с округлением вверх); </li><li> текущее время $$$\ge b_i$$$. </li></ol><p>Так как Леша потратил все силы на предсказание задержек, помогите ему посчитать время <span class="tex-font-style-bf">прибытия</span> на станцию $$$n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество станций.</p><p>Далее заданы $$$n$$$ строк, в каждой из которых содержится два целых числа: $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i &lt; b_i \le 10^6$$$). Гарантируется, что $$$b_i &lt; a_{i+1}$$$. </p><p>В следующей строке заданы $$$n$$$ целых чисел $$$tm_1, tm_2, \dots, tm_n$$$ ($$$0 \le tm_i \le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — время прибытия Леши на последнюю станцию.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 4 10 12 0 2 5 1 4 7 8 9 10 13 15 19 20 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 32 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Леша сначала пребывает без опоздания на станцию номер $$$1$$$ в момент времени $$$a_1 = 2$$$ (так как $$$tm_1 = 0$$$). Затем отъезжает с неё в момент времени $$$b_1 = 4$$$. На станцию номер $$$2$$$ он приезжает с опозданием на $$$tm_2 = 2$$$ единицы времени, то есть в $$$12$$$.</p><p>Во втором наборе, Леша прибывает на первую станцию с опозданием в $$$tm_1 = 1$$$, то есть в момент $$$2$$$. Далее поезд должен пробыть хотя бы $$$\left\lceil \frac{b_1 - a_1}{2} \right\rceil = 2$$$ единицы времени на станции и отправится не ранее чем в момент $$$b_1 = 4$$$. Таким образом, поезд оправляется с первой станции в момент $$$4$$$.</p><p>Разбирая аналогичным образом следующие станции, можно получить, что поезд прибудет на вторую станцию в момент $$$9$$$, а покинет в $$$10$$$; на третью станцию прибудет в $$$14$$$, покинет в $$$15$$$; на четвертую: прибудет в $$$22$$$, покинет в $$$23$$$. И, наконец, прибудет на пятую в $$$32$$$.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:44</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be664a377b53',t:'MTY5NjY2NzAyNC42NjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1501B
1501
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>На этой неделе Аркадий хотел последовать традициям, испечь стопку блинов и придумать про это задачу. Однако он вспомнил, что чтобы придумать задачу про стопки блинов, нужно работать в одной известной IT-компании, поэтому вместо этого Аркадий решил испечь торт «Наполеон».</p><p>Чтобы испечь торт «Наполеон», нужно сначала выпечь $$$n$$$ сухих коржей (слоев), а затем сложить их друг на друга, пропитывая кремом. Аркадий начал с пустого блюда, и повторил следующие шаги $$$n$$$ раз: </p><ul> <li> положил новый сухой слой на верх стопки; </li><li> после того, как он положил $$$i$$$-й слой, он добавил на верх стопки $$$a_i$$$ ложек крема. </li></ul><p>Когда Аркадий добавляет $$$x$$$ ложек крема на верх стопки, $$$x$$$ верхних слоев торта пропитываются кремом. Если с торте в этот момент меньше $$$x$$$ слоев, то пропитываются все эти слои, а оставшийся крем пропадает. Если $$$x = 0$$$, то не пропитывается ни один слой.</p><center> <img class="tex-graphics" height="76px" src="https://espresso.codeforces.com/45fb6f7967c5e2a07c667a087c2b9602e4fd8373.png" style="max-width: 100.0%;max-height: 100.0%;" width="567px"/> <span class="tex-font-size-small">Рисунок иллюстрирует первый набор входных данных из примера.</span> </center><p>Помогите Аркадию определить, какие слои окажутся пропитаны кремом, когда он закончит собирать торт, а какие нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 20\,000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество слоев в торте.</p><p>Вторая строка каждого набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$) — объем крема, добавленного после добавления каждого слоя.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку с $$$n$$$ целыми числами. $$$i$$$-е из этих чисел должно быть равно $$$1$$$, если $$$i$$$-й слой снизу окажется пропитанным, и $$$0$$$ иначе.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 6 0 3 0 0 1 3 10 0 0 0 1 0 5 0 0 0 2 3 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 0 1 1 1 0 1 1 1 1 1 0 0 1 1 0 0 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b9ab79ea921d691392bf39da98577058"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="f0a97110320a5fea54a4b1c029103cf455e47f8f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b9ab79ea921d691392bf39da98577058'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1501%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='b9ab79ea921d691392bf39da98577058'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1501">Codeforces Round 707 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='b9ab79ea921d691392bf39da98577058'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1501/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='b9ab79ea921d691392bf39da98577058'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922987"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b9ab79ea921d691392bf39da98577058'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922987"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13264:13265" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13275" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1501">Задачи</a></li> <li><a href="/contest/1501/submit">Отослать</a></li> <li><a href="/contest/1501/my">Мои посылки</a></li> <li><a href="/contest/1501/status">Статус</a></li> <li><a href="/contest/1501/hacks">Взломы</a></li> <li><a href="/contest/1501/room/1">Комната</a></li> <li><a href="/contest/1501/standings">Положение</a></li> <li><a href="/contest/1501/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_30408eca0eea811349185219b2bccf61c70eb60f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>На этой неделе Аркадий хотел последовать традициям, испечь стопку блинов и придумать про это задачу. Однако он вспомнил, что чтобы придумать задачу про стопки блинов, нужно работать в одной известной IT-компании, поэтому вместо этого Аркадий решил испечь торт «Наполеон».</p><p>Чтобы испечь торт «Наполеон», нужно сначала выпечь $$$n$$$ сухих коржей (слоев), а затем сложить их друг на друга, пропитывая кремом. Аркадий начал с пустого блюда, и повторил следующие шаги $$$n$$$ раз: </p><ul> <li> положил новый сухой слой на верх стопки; </li><li> после того, как он положил $$$i$$$-й слой, он добавил на верх стопки $$$a_i$$$ ложек крема. </li></ul><p>Когда Аркадий добавляет $$$x$$$ ложек крема на верх стопки, $$$x$$$ верхних слоев торта пропитываются кремом. Если с торте в этот момент меньше $$$x$$$ слоев, то пропитываются все эти слои, а оставшийся крем пропадает. Если $$$x = 0$$$, то не пропитывается ни один слой.</p><center> <img class="tex-graphics" height="76px" src="https://espresso.codeforces.com/45fb6f7967c5e2a07c667a087c2b9602e4fd8373.png" style="max-width: 100.0%;max-height: 100.0%;" width="567px" /> <span class="tex-font-size-small">Рисунок иллюстрирует первый набор входных данных из примера.</span> </center><p>Помогите Аркадию определить, какие слои окажутся пропитаны кремом, когда он закончит собирать торт, а какие нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 20\,000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество слоев в торте.</p><p>Вторая строка каждого набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$) — объем крема, добавленного после добавления каждого слоя.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку с $$$n$$$ целыми числами. $$$i$$$-е из этих чисел должно быть равно $$$1$$$, если $$$i$$$-й слой снизу окажется пропитанным, и $$$0$$$ иначе.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 6 0 3 0 0 1 3 10 0 0 0 1 0 5 0 0 0 2 3 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 0 1 1 1 0 1 1 1 1 1 0 0 1 1 0 0 0 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:46</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be6feb169da8',t:'MTY5NjY2NzAyNi4wMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*900"]
1501C
1501
C
ru
C. Поеду домой
<div class="problem-statement"><div class="header"><div class="title">C. Поеду домой</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На третьем месяце дистанционного обучения студентке Насте стало скучно, и она решила поехать домой к себе в родной город на пару недель с целью развеяться. Чтобы ей было веселее в дороге, её друг подарил ей массив целых чисел $$$a$$$. </p><p>Шел пятый час поездки, и Настя вспомнила про подарок. Чтобы развлечь себя, она решила проверить, можно ли выбрать четыре <span class="tex-font-style-bf">различных</span> индекса $$$x, y, z, w$$$ таких, что $$$a_x + a_y = a_z + a_w$$$.</p><p>Занявшись этим делом, Настя не заметила, как прошло время, и её поезд уже пришел на станцию назначения. Она не успела закончить проверку, но всё ещё хочет узнать истину. Сможете ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — количество чисел в массиве.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$).</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>Если они существуют, далее выведите сами индексы $$$x$$$, $$$y$$$, $$$z$$$ и $$$w$$$ ($$$1 \le x, y, z, w \le n$$$).</p><p>Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 5 2 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 1 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 1 9 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Обратите внимание, что ответ <span class="tex-font-style-tt">2 3 4 6</span> также подходит.</p><p>Во втором примере нельзя выбрать четыре таких индекса. Ответ <span class="tex-font-style-tt">1 2 2 3</span> не подходит, потому что в нем не все индексы различны, хоть и $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_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="e20e65f38651dca65fb84c13c438d645"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="f0a97110320a5fea54a4b1c029103cf455e47f8f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e20e65f38651dca65fb84c13c438d645'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1501%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='e20e65f38651dca65fb84c13c438d645'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1501">Codeforces Round 707 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e20e65f38651dca65fb84c13c438d645'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1501/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='e20e65f38651dca65fb84c13c438d645'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922988"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e20e65f38651dca65fb84c13c438d645'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922988"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13264:13265" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13275" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1501">Задачи</a></li> <li><a href="/contest/1501/submit">Отослать</a></li> <li><a href="/contest/1501/my">Мои посылки</a></li> <li><a href="/contest/1501/status">Статус</a></li> <li><a href="/contest/1501/hacks">Взломы</a></li> <li><a href="/contest/1501/room/1">Комната</a></li> <li><a href="/contest/1501/standings">Положение</a></li> <li><a href="/contest/1501/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c7bd1d92feaf0b5c74dcadc4005c9d64cf74c796"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Поеду домой</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На третьем месяце дистанционного обучения студентке Насте стало скучно, и она решила поехать домой к себе в родной город на пару недель с целью развеяться. Чтобы ей было веселее в дороге, её друг подарил ей массив целых чисел $$$a$$$. </p><p>Шел пятый час поездки, и Настя вспомнила про подарок. Чтобы развлечь себя, она решила проверить, можно ли выбрать четыре <span class="tex-font-style-bf">различных</span> индекса $$$x, y, z, w$$$ таких, что $$$a_x + a_y = a_z + a_w$$$.</p><p>Занявшись этим делом, Настя не заметила, как прошло время, и её поезд уже пришел на станцию назначения. Она не успела закончить проверку, но всё ещё хочет узнать истину. Сможете ей помочь?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — количество чисел в массиве.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$).</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>Если они существуют, далее выведите сами индексы $$$x$$$, $$$y$$$, $$$z$$$ и $$$w$$$ ($$$1 \le x, y, z, w \le n$$$).</p><p>Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 5 2 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 2 3 1 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 1 9 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Обратите внимание, что ответ <span class="tex-font-style-tt">2 3 4 6</span> также подходит.</p><p>Во втором примере нельзя выбрать четыре таких индекса. Ответ <span class="tex-font-style-tt">1 2 2 3</span> не подходит, потому что в нем не все индексы различны, хоть и $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:47</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be7878c19d98',t:'MTY5NjY2NzAyNy4zMTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1800"]
1501D
1501
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>В продаже было несколько люстр, отличающихся друг от друга набором цветов в цикле или порядком. По какой-то ошибке, а может из-за невнимательности, человек, ответственный за выбор люстр, купил две разные люстры.</p><p>Из-за того, что люстры разные, в некоторые дни они будут светить одинаково, а в некоторые — по-разному. Естественно, это не солидно, и вообще раздражает Васю, так что когда в $$$k$$$-й раз наступит событие «сегодня люстры светят разными цветами», Вася очень разозлится и кого-то уволит (вероятно, сотрудника, купившего люстры). Ваша задача – понять, на какой день, начиная со дня установки люстр, это случится. Считайте, что Вася очень любит работать, поэтому работает каждый день, без праздников и выходных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — количество цветов в первой люстре, количество цветов во второй люстре и сколько раз люстры должны гореть разным цветом, чтобы Вася очень разозлился.</p><p>Во второй строке даны $$$n$$$ <span class="tex-font-style-bf">различных</span> чисел $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для первой люстры.</p><p>В третьей строке даны $$$m$$$ <span class="tex-font-style-bf">различных</span> чисел $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для второй люстры.</p><p>В $$$i$$$-й день первая люстра светит цветом $$$a_x$$$, где $$$x = ((i - 1) \mod n) + 1)$$$, а вторая цветом $$$b_y$$$, где $$$y = ((i - 1) \mod m) + 1)$$$.</p><p>Гарантируется, что последовательность $$$a$$$ не совпадает тождественно с последовательностью $$$b$$$, а значит лампы будут периодически раздражать Васю.</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 4 4 2 3 1 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 8 41 1 3 2 1 6 4 3 5 7 2 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 47 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 31 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 62 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте из условия люстры будут гореть разными цветами в дни $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$. Соответственно ответом является $$$5$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e29d60ff5c667d63c4ce3a7ae0b108d3"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="f0a97110320a5fea54a4b1c029103cf455e47f8f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e29d60ff5c667d63c4ce3a7ae0b108d3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1501%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='e29d60ff5c667d63c4ce3a7ae0b108d3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1501">Codeforces Round 707 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e29d60ff5c667d63c4ce3a7ae0b108d3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1501/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Китайская теорема об остатках, алгоритм Гарнера"> китайская теорема об остатках </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='e29d60ff5c667d63c4ce3a7ae0b108d3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922989"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e29d60ff5c667d63c4ce3a7ae0b108d3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922989"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13264:13265" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13275" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1501">Задачи</a></li> <li><a href="/contest/1501/submit">Отослать</a></li> <li><a href="/contest/1501/my">Мои посылки</a></li> <li><a href="/contest/1501/status">Статус</a></li> <li><a href="/contest/1501/hacks">Взломы</a></li> <li><a href="/contest/1501/room/1">Комната</a></li> <li><a href="/contest/1501/standings">Положение</a></li> <li><a href="/contest/1501/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2e09f1160c79ddf0b794597701005659f78d954d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>В продаже было несколько люстр, отличающихся друг от друга набором цветов в цикле или порядком. По какой-то ошибке, а может из-за невнимательности, человек, ответственный за выбор люстр, купил две разные люстры.</p><p>Из-за того, что люстры разные, в некоторые дни они будут светить одинаково, а в некоторые — по-разному. Естественно, это не солидно, и вообще раздражает Васю, так что когда в $$$k$$$-й раз наступит событие «сегодня люстры светят разными цветами», Вася очень разозлится и кого-то уволит (вероятно, сотрудника, купившего люстры). Ваша задача – понять, на какой день, начиная со дня установки люстр, это случится. Считайте, что Вася очень любит работать, поэтому работает каждый день, без праздников и выходных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — количество цветов в первой люстре, количество цветов во второй люстре и сколько раз люстры должны гореть разным цветом, чтобы Вася очень разозлился.</p><p>Во второй строке даны $$$n$$$ <span class="tex-font-style-bf">различных</span> чисел $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для первой люстры.</p><p>В третьей строке даны $$$m$$$ <span class="tex-font-style-bf">различных</span> чисел $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$), задающих последовательность цветов для второй люстры.</p><p>В $$$i$$$-й день первая люстра светит цветом $$$a_x$$$, где $$$x = ((i - 1) \mod n) + 1)$$$, а вторая цветом $$$b_y$$$, где $$$y = ((i - 1) \mod m) + 1)$$$.</p><p>Гарантируется, что последовательность $$$a$$$ не совпадает тождественно с последовательностью $$$b$$$, а значит лампы будут периодически раздражать Васю.</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 4 4 2 3 1 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 8 41 1 3 2 1 6 4 3 5 7 2 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 47 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 31 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 62 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте из условия люстры будут гореть разными цветами в дни $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$. Соответственно ответом является $$$5$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:48</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be8248a29d45',t:'MTY5NjY2NzAyOC44ODkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0438\u0442\u0430\u0439\u0441\u043a\u0430\u044f \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u043e\u0431 \u043e\u0441\u0442\u0430\u0442\u043a\u0430\u0445, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0413\u0430\u0440\u043d\u0435\u0440\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043a\u0438\u0442\u0430\u0439\u0441\u043a\u0430\u044f \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u043e\u0431 \u043e\u0441\u0442\u0430\u0442\u043a\u0430\u0445", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2200"]
1501E
1501
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$$$ и $$$B$$$ размера $$$n \times m$$$. </p><p>Назовём <span class="tex-font-style-it">сортировкой по столбцу</span> следующее действие: выбирается столбец, и все строки упорядочиваются по значению в этом столбце, от строк, содержащих меньшие значения, к строкам с большими. В случае, если две строки имеют одинаковое значение в этом столбце, их порядок не меняется (такие сортировки называются <span class="tex-font-style-it">стабильными</span>).</p><p>Подобное поведение сортировки по столбцу можно найти практически в любом офисном приложении для работы с таблицами. Петя работает в одном из таких приложений, и у него открыта таблица $$$A$$$. Он хочет проделать ноль или более операций сортировки по столбцу, чтобы получить таблицу $$$B$$$.</p><p>Определите, может ли он это сделать, и если может, предложите ему алгоритм действий — последовательность столбцов, по которым нужно применить сортировку по столбцу. Обратите внимание, что <span class="tex-font-style-bf">не требуется</span> минимизировать число действий.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 1500$$$) — размеры таблицы.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$a_{i,j}$$$ ($$$1 \le a_{i, j} \le n$$$) — элементы таблицы $$$A$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$b_{i, j}$$$ ($$$1 \le b_{i, j} \le n$$$) — элементы таблицы $$$B$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если превратить таблицу $$$A$$$ в таблицу $$$B$$$ невозможно, выведите $$$-1$$$.</p><p>В противном случае выведите $$$k$$$ ($$$0 \le k \le 5000$$$) — количество сортировок, которые нужно сделать.</p><p>Затем выведите $$$k$$$ целых чисел $$$c_1, \ldots, c_k$$$ ($$$1 \le c_i \le m$$$) — номера столбцов, по которым нужно сделать сортировку.</p><p>Можно доказать, что если Петя может осуществить желаемое, то $$$5000$$$ действий ему хватит.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 2 1 2 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 1 2 1 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 2 1 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим второй пример. После сортировки по первому столбцу таблица имеет вид</p><p>$$$$$$\begin{matrix} 1&amp;3&amp;3\\ 1&amp;1&amp;2\\ 2&amp;3&amp;2. \end{matrix}$$$$$$</p><p>После того, как мы отсортируем таблицу по второму столбцу, она станет</p><p>$$$$$$\begin{matrix} 1&amp;1&amp;2\\ 1&amp;3&amp;3\\ 2&amp;3&amp;2, \end{matrix}$$$$$$</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="5628ac482ad539eaf34d85db4c03433d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="f0a97110320a5fea54a4b1c029103cf455e47f8f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='5628ac482ad539eaf34d85db4c03433d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1501%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='5628ac482ad539eaf34d85db4c03433d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1501">Codeforces Round 707 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='5628ac482ad539eaf34d85db4c03433d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1501/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound 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='5628ac482ad539eaf34d85db4c03433d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922990"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5628ac482ad539eaf34d85db4c03433d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922990"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13264:13265" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13275" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1501">Задачи</a></li> <li><a href="/contest/1501/submit">Отослать</a></li> <li><a href="/contest/1501/my">Мои посылки</a></li> <li><a href="/contest/1501/status">Статус</a></li> <li><a href="/contest/1501/hacks">Взломы</a></li> <li><a href="/contest/1501/room/1">Комната</a></li> <li><a href="/contest/1501/standings">Положение</a></li> <li><a href="/contest/1501/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5f92b1fbc5f7c12f19c6c322aab1465e7baccb5b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$ и $$$B$$$ размера $$$n \times m$$$. </p><p>Назовём <span class="tex-font-style-it">сортировкой по столбцу</span> следующее действие: выбирается столбец, и все строки упорядочиваются по значению в этом столбце, от строк, содержащих меньшие значения, к строкам с большими. В случае, если две строки имеют одинаковое значение в этом столбце, их порядок не меняется (такие сортировки называются <span class="tex-font-style-it">стабильными</span>).</p><p>Подобное поведение сортировки по столбцу можно найти практически в любом офисном приложении для работы с таблицами. Петя работает в одном из таких приложений, и у него открыта таблица $$$A$$$. Он хочет проделать ноль или более операций сортировки по столбцу, чтобы получить таблицу $$$B$$$.</p><p>Определите, может ли он это сделать, и если может, предложите ему алгоритм действий — последовательность столбцов, по которым нужно применить сортировку по столбцу. Обратите внимание, что <span class="tex-font-style-bf">не требуется</span> минимизировать число действий.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 1500$$$) — размеры таблицы.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$a_{i,j}$$$ ($$$1 \le a_{i, j} \le n$$$) — элементы таблицы $$$A$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ целых чисел $$$b_{i, j}$$$ ($$$1 \le b_{i, j} \le n$$$) — элементы таблицы $$$B$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если превратить таблицу $$$A$$$ в таблицу $$$B$$$ невозможно, выведите $$$-1$$$.</p><p>В противном случае выведите $$$k$$$ ($$$0 \le k \le 5000$$$) — количество сортировок, которые нужно сделать.</p><p>Затем выведите $$$k$$$ целых чисел $$$c_1, \ldots, c_k$$$ ($$$1 \le c_i \le m$$$) — номера столбцов, по которым нужно сделать сортировку.</p><p>Можно доказать, что если Петя может осуществить желаемое, то $$$5000$$$ действий ему хватит.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 2 1 2 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 3 2 1 3 3 1 1 2 1 1 2 1 3 3 2 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 1 1 2 1 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 2 2 1 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим второй пример. После сортировки по первому столбцу таблица имеет вид</p><p>$$$$$$\begin{matrix} 1&amp;3&amp;3\\ 1&amp;1&amp;2\\ 2&amp;3&amp;2. \end{matrix}$$$$$$</p><p>После того, как мы отсортируем таблицу по второму столбцу, она станет</p><p>$$$$$$\begin{matrix} 1&amp;1&amp;2\\ 1&amp;3&amp;3\\ 2&amp;3&amp;2, \end{matrix}$$$$$$</p><p>что нам и нужно.</p><p>В третьем тесте любая сортировка не меняет таблицу, так как все столбцы уже отсортированы.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:50</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be8a4fff16db',t:'MTY5NjY2NzAzMC4xNjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
["*2600"]
1501F
1501
F
ru
F. Плитка для ванной
<div class="problem-statement"><div class="header"><div class="title">F. Плитка для ванной</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>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>У Кости очень много дел: ремонт в самом разгаре! Надо клеить обои, собирать мебель и постоянно вывозить мусор.</p><p>Сегодня Костя хочет купить плитку для ванной. Он пришел в магазин и оказался перед большим квадратным стендом с плиткой. Стенд представляет из себя квадрат из $$$n \times n$$$ клеток, каждая клетка которого — маленький кусочек плитки цвета $$$c_{i,\,j}$$$. Магазин продает кусочки плитки пакетами, а именно, купить можно только подквадрат исходного квадрата.</p><p>Подквадратом называется любой квадратный фрагмент стенда, то есть любое множество $$$S(i_0, j_0, k) = \{c_{i,\,j}\ |\ i_0 \le i &lt; i_0 + k, j_0 \le j &lt; j_0 + k\}$$$ при $$$1 \le i_0, j_0 \le n - k + 1$$$.</p><p>Костя еще не знает, сколько кусочков плитки он хочет купить, и, соответственно, рассматривает подквадраты всех возможных размеров. При этом он точно не хочет слишком разноцветную плитку в ванной, что позволяет ему сузить выбор. Помогите Косте для каждого $$$k \le n$$$ определить количество различных подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов плитки. Подквадраты считаются различными, если их расположение на стенде не совпадает.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых положительных числа $$$n$$$, $$$q$$$ ($$$1 \le n \le 1500$$$, $$$1 \le q \le 10$$$) — размер стенда с плитками и ограничение на количество различных цветов в пакете.</p><p>В следующих $$$n$$$ строках находятся по $$$n$$$ целых положительных чисел $$$c_{i,\,j}$$$ ($$$1 \le c_{i,\,j} \le n^2$$$): $$$j$$$-е число в $$$i$$$-й строке соответствует цвету плитки в клетке $$$(i,\,j)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$ выведите в отдельной строке по одному целому числу — количество подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 9 4 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все цвета квадратиков плитки различные. Поскольку Костя не хочет, чтобы в купленном квадрате было больше $$$4$$$ цветов, он может купить себе любой подквадрат размера $$$1 \times 1$$$ или $$$2 \times 2$$$, но при этом не сможет купить квадрат размера $$$3 \times 3$$$.</p><p>Во втором примере есть повторяющиеся цвета. А именно, за счет ограничения $$$q = 8$$$ Костя может купить любой подквадрат $$$1 \times 1$$$ и $$$2 \times 2$$$, а также любой подквадрат $$$3 \times 3$$$, ведь в каждом таком подквадрате всего $$$7$$$ цветов. Весь стенд размера $$$4 \times 4$$$ Костя купить не сможет, потому что там будет $$$9$$$ цветов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="81b187884b70ffbf9ab0054dd0a81f66"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="f0a97110320a5fea54a4b1c029103cf455e47f8f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='81b187884b70ffbf9ab0054dd0a81f66'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1501%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='81b187884b70ffbf9ab0054dd0a81f66'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1501">Codeforces Round 707 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='81b187884b70ffbf9ab0054dd0a81f66'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1501/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound 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='81b187884b70ffbf9ab0054dd0a81f66'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="922991"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='81b187884b70ffbf9ab0054dd0a81f66'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="922991"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88590" title="Codeforces Round #707 (Div.1, Div.2, по Открытой олимпиаде школьников по информатике, рейтинговый)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13264:13265" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/88591" title="Codeforces Round #707 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13275" resourceName="Codeforces Round #707 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1501">Задачи</a></li> <li><a href="/contest/1501/submit">Отослать</a></li> <li><a href="/contest/1501/my">Мои посылки</a></li> <li><a href="/contest/1501/status">Статус</a></li> <li><a href="/contest/1501/hacks">Взломы</a></li> <li><a href="/contest/1501/room/1">Комната</a></li> <li><a href="/contest/1501/standings">Положение</a></li> <li><a href="/contest/1501/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3d591f7cbabffe700e5fa7008554c7c414d7fc07"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>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>У Кости очень много дел: ремонт в самом разгаре! Надо клеить обои, собирать мебель и постоянно вывозить мусор.</p><p>Сегодня Костя хочет купить плитку для ванной. Он пришел в магазин и оказался перед большим квадратным стендом с плиткой. Стенд представляет из себя квадрат из $$$n \times n$$$ клеток, каждая клетка которого — маленький кусочек плитки цвета $$$c_{i,\,j}$$$. Магазин продает кусочки плитки пакетами, а именно, купить можно только подквадрат исходного квадрата.</p><p>Подквадратом называется любой квадратный фрагмент стенда, то есть любое множество $$$S(i_0, j_0, k) = \{c_{i,\,j}\ |\ i_0 \le i &lt; i_0 + k, j_0 \le j &lt; j_0 + k\}$$$ при $$$1 \le i_0, j_0 \le n - k + 1$$$.</p><p>Костя еще не знает, сколько кусочков плитки он хочет купить, и, соответственно, рассматривает подквадраты всех возможных размеров. При этом он точно не хочет слишком разноцветную плитку в ванной, что позволяет ему сузить выбор. Помогите Косте для каждого $$$k \le n$$$ определить количество различных подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов плитки. Подквадраты считаются различными, если их расположение на стенде не совпадает.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых положительных числа $$$n$$$, $$$q$$$ ($$$1 \le n \le 1500$$$, $$$1 \le q \le 10$$$) — размер стенда с плитками и ограничение на количество различных цветов в пакете.</p><p>В следующих $$$n$$$ строках находятся по $$$n$$$ целых положительных чисел $$$c_{i,\,j}$$$ ($$$1 \le c_{i,\,j} \le n^2$$$): $$$j$$$-е число в $$$i$$$-й строке соответствует цвету плитки в клетке $$$(i,\,j)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого $$$k$$$ от $$$1$$$ до $$$n$$$ выведите в отдельной строке по одному целому числу — количество подквадратов размера $$$k \times k$$$, в которых не более $$$q$$$ различных цветов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 2 3 4 5 6 7 8 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 9 4 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все цвета квадратиков плитки различные. Поскольку Костя не хочет, чтобы в купленном квадрате было больше $$$4$$$ цветов, он может купить себе любой подквадрат размера $$$1 \times 1$$$ или $$$2 \times 2$$$, но при этом не сможет купить квадрат размера $$$3 \times 3$$$.</p><p>Во втором примере есть повторяющиеся цвета. А именно, за счет ограничения $$$q = 8$$$ Костя может купить любой подквадрат $$$1 \times 1$$$ и $$$2 \times 2$$$, а также любой подквадрат $$$3 \times 3$$$, ведь в каждом таком подквадрате всего $$$7$$$ цветов. Весь стенд размера $$$4 \times 4$$$ Костя купить не сможет, потому что там будет $$$9$$$ цветов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:51</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be924b119d6a',t:'MTY5NjY2NzAzMS40NzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "*2900"]
1503A
1503
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-tt">+</span>' и '<span class="tex-font-style-tt">1</span>'. Например, последовательности «<span class="tex-font-style-tt">(())()</span>», «<span class="tex-font-style-tt">()</span>» и «<span class="tex-font-style-tt">(()(()))</span>» являются сбалансированными, а «<span class="tex-font-style-tt">)(</span>», «<span class="tex-font-style-tt">(()</span>» и «<span class="tex-font-style-tt">(()))(</span>» — нет.</p><p>Вам дана бинарная строка $$$s$$$ длины $$$n$$$. Постройте две сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$ длины $$$n$$$ такие, что для всех $$$1\le i\le n$$$ выполняется: </p><ul> <li> если $$$s_i=1$$$, то $$$a_i=b_i$$$ </li><li> если $$$s_i=0$$$, то $$$a_i\ne b_i$$$ </li></ul><p>Если это невозможно, вы должны это определить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое число $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ — четное).</p><p>Следующая строка содержит строку $$$s$$$ длины $$$n$$$, состоящую из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Сумма $$$n$$$ во всех тестовых случаях не превышает $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если такие две сбалансированные скобочные последовательности существуют, выведите «<span class="tex-font-style-tt">YES</span>» в первой строке, иначе выведите «<span class="tex-font-style-tt">NO</span>». Вы можете выводить каждый символ в любом регистре.</p><p>Если ответ «<span class="tex-font-style-tt">YES</span>», в двух следующих строках выведите сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$, удовлетворяющие условиям.</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 6 101101 10 1001101101 4 1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES ()()() ((())) YES ()()((())) (())()()() NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()()</span>» и $$$b=$$$«<span class="tex-font-style-tt">((()))</span>». Символы равны в позициях $$$1$$$, $$$3$$$, $$$4$$$ и $$$6$$$, ровно в тех позициях, где $$$s_i=1$$$.</p><p>Во втором наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()((()))</span>» и $$$b=$$$«<span class="tex-font-style-tt">(())()()()</span>». Символы равны в позициях $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, ровно в тех позициях, где $$$s_i=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="badb4eb149cd66cf9b6d82203dcfa4ae"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="859c69031442a2c7b37200788e3a5d4f0a696bd0"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='badb4eb149cd66cf9b6d82203dcfa4ae'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1503%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='badb4eb149cd66cf9b6d82203dcfa4ae'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1503">Codeforces Round 712 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='badb4eb149cd66cf9b6d82203dcfa4ae'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1503/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='badb4eb149cd66cf9b6d82203dcfa4ae'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945469"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='badb4eb149cd66cf9b6d82203dcfa4ae'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945469"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13429" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13437" resourceName="T" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1503">Задачи</a></li> <li><a href="/contest/1503/submit">Отослать</a></li> <li><a href="/contest/1503/my">Мои посылки</a></li> <li><a href="/contest/1503/status">Статус</a></li> <li><a href="/contest/1503/hacks">Взломы</a></li> <li><a href="/contest/1503/room/1">Комната</a></li> <li><a href="/contest/1503/standings">Положение</a></li> <li><a href="/contest/1503/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_61a4858eeca539ddab34c1541aa9f21869e969f9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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-tt">+</span>' и '<span class="tex-font-style-tt">1</span>'. Например, последовательности «<span class="tex-font-style-tt">(())()</span>», «<span class="tex-font-style-tt">()</span>» и «<span class="tex-font-style-tt">(()(()))</span>» являются сбалансированными, а «<span class="tex-font-style-tt">)(</span>», «<span class="tex-font-style-tt">(()</span>» и «<span class="tex-font-style-tt">(()))(</span>» — нет.</p><p>Вам дана бинарная строка $$$s$$$ длины $$$n$$$. Постройте две сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$ длины $$$n$$$ такие, что для всех $$$1\le i\le n$$$ выполняется: </p><ul> <li> если $$$s_i=1$$$, то $$$a_i=b_i$$$ </li><li> если $$$s_i=0$$$, то $$$a_i\ne b_i$$$ </li></ul><p>Если это невозможно, вы должны это определить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое число $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ — четное).</p><p>Следующая строка содержит строку $$$s$$$ длины $$$n$$$, состоящую из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Сумма $$$n$$$ во всех тестовых случаях не превышает $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если такие две сбалансированные скобочные последовательности существуют, выведите «<span class="tex-font-style-tt">YES</span>» в первой строке, иначе выведите «<span class="tex-font-style-tt">NO</span>». Вы можете выводить каждый символ в любом регистре.</p><p>Если ответ «<span class="tex-font-style-tt">YES</span>», в двух следующих строках выведите сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$, удовлетворяющие условиям.</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 6 101101 10 1001101101 4 1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES ()()() ((())) YES ()()((())) (())()()() NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()()</span>» и $$$b=$$$«<span class="tex-font-style-tt">((()))</span>». Символы равны в позициях $$$1$$$, $$$3$$$, $$$4$$$ и $$$6$$$, ровно в тех позициях, где $$$s_i=1$$$.</p><p>Во втором наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()((()))</span>» и $$$b=$$$«<span class="tex-font-style-tt">(())()()()</span>». Символы равны в позициях $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, ровно в тех позициях, где $$$s_i=1$$$.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:53</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124be9a681f1687',t:'MTY5NjY2NzAzMy4wNzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1600"]
1503B
1503
B
ru
B. 3-раскраска
<div class="problem-statement"><div class="header"><div class="title">B. 3-раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Алиса и Боб играют в игру. Есть доска $$$n\times n$$$, изначально пустая. Мы будем обозначать ячейку в строке $$$i$$$ и столбце $$$j$$$ как $$$(i, j)$$$ для $$$1\le i, j\le n$$$. Также, есть бесконечный запас фишек $$$3$$$ цветов, обозначенных $$$1$$$, $$$2$$$ и $$$3$$$.</p><p>Алиса и Боб ходят по очереди по следующим правилам: каждый ход начинается с того, что Алиса называет один из трех цветов, назовем его $$$a$$$. Затем Боб выбирает цвет $$$b\ne a$$$, выбирает пустую ячейку и помещает на нее фишку цвета $$$b$$$.</p><p>Мы говорим, что случился <span class="tex-font-style-bf">конфликт</span>, если есть две соседние ячейки, содержащие фишки одного цвета. Две ячейки считаются соседними, если у них есть общая сторона.</p><p>Если в какой-то момент возникает конфликт, Алиса побеждает. В противном случае, если было совершено $$$n^2$$$ ходов (так что доска полностью заполнилась) без конфликтов, побеждает Боб.</p><p>У нас есть доказательство того, что у Боба есть выигрышная стратегия. Сыграйте в игру за Боба и выиграйте.</p><p>Интерактор <span class="tex-font-style-bf">адаптивен</span>. Таким образом, выбор цвета Алисой может зависеть от предыдущих ходов Боба.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с чтения единственного целого числа $$$n$$$ ($$$2\le n\le 100$$$) — размера доски.</p><p>Дальше начинаются ходы. Каждый ход следует начинать с чтения целого $$$a$$$ ($$$1\le a\le 3$$$) — выбранного цвета Алисы.</p><p>Затем необходимо вывести три целых числа $$$b,i,j$$$ ($$$1\le b\le 3,b\ne a, 1\le i,j\le n$$$) —, что означает, что Боб кладет в ячейку $$$(i, j)$$$ фишку цвета $$$b$$$. Ячейка $$$(i, j)$$$ не должна содержать фишки из предыдущих ходов. Если ваш ход недействителен или проигрывает партию, взаимодействие прекратится и вы получите вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>После того как все $$$n^2$$$ ходов были сделаны, завершите программу, чтобы избежать неожиданных вердиктов.</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 100$$$).</p><p>Вторая строка содержит $$$n^2$$$ целых чисел $$$a_1,\ldots,a_{n^2}$$$ ($$$1\le a_i\le 3$$$), где $$$a_i$$$ обозначает цвет Алисы на $$$i$$$-м ходу игры.</p><p>Интерактор может отклониться от заданного во взломе порядка цветов, но только в том случае, если это заставит Боба проиграть.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 3 1 2 3 2 1 1 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Конечное состояние доски из примера изображено ниже. Боб выигрывает, потому что нет двух соседних ячеек с фишками одного и того же цвета. $$$$$$\begin{matrix}2&amp;3\\3&amp;1\end{matrix}$$$$$$</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="157e9db9614fb9d6c1a252b9f62746d6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="859c69031442a2c7b37200788e3a5d4f0a696bd0"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='157e9db9614fb9d6c1a252b9f62746d6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1503%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='157e9db9614fb9d6c1a252b9f62746d6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1503">Codeforces Round 712 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='157e9db9614fb9d6c1a252b9f62746d6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1503/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди"> игры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='157e9db9614fb9d6c1a252b9f62746d6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945470"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='157e9db9614fb9d6c1a252b9f62746d6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945470"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13429" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13437" resourceName="T" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1503">Задачи</a></li> <li><a href="/contest/1503/submit">Отослать</a></li> <li><a href="/contest/1503/my">Мои посылки</a></li> <li><a href="/contest/1503/status">Статус</a></li> <li><a href="/contest/1503/hacks">Взломы</a></li> <li><a href="/contest/1503/room/1">Комната</a></li> <li><a href="/contest/1503/standings">Положение</a></li> <li><a href="/contest/1503/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8450b857472f0159e0d3c81922f0d60187453c78"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. 3-раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Алиса и Боб играют в игру. Есть доска $$$n\times n$$$, изначально пустая. Мы будем обозначать ячейку в строке $$$i$$$ и столбце $$$j$$$ как $$$(i, j)$$$ для $$$1\le i, j\le n$$$. Также, есть бесконечный запас фишек $$$3$$$ цветов, обозначенных $$$1$$$, $$$2$$$ и $$$3$$$.</p><p>Алиса и Боб ходят по очереди по следующим правилам: каждый ход начинается с того, что Алиса называет один из трех цветов, назовем его $$$a$$$. Затем Боб выбирает цвет $$$b\ne a$$$, выбирает пустую ячейку и помещает на нее фишку цвета $$$b$$$.</p><p>Мы говорим, что случился <span class="tex-font-style-bf">конфликт</span>, если есть две соседние ячейки, содержащие фишки одного цвета. Две ячейки считаются соседними, если у них есть общая сторона.</p><p>Если в какой-то момент возникает конфликт, Алиса побеждает. В противном случае, если было совершено $$$n^2$$$ ходов (так что доска полностью заполнилась) без конфликтов, побеждает Боб.</p><p>У нас есть доказательство того, что у Боба есть выигрышная стратегия. Сыграйте в игру за Боба и выиграйте.</p><p>Интерактор <span class="tex-font-style-bf">адаптивен</span>. Таким образом, выбор цвета Алисой может зависеть от предыдущих ходов Боба.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с чтения единственного целого числа $$$n$$$ ($$$2\le n\le 100$$$) — размера доски.</p><p>Дальше начинаются ходы. Каждый ход следует начинать с чтения целого $$$a$$$ ($$$1\le a\le 3$$$) — выбранного цвета Алисы.</p><p>Затем необходимо вывести три целых числа $$$b,i,j$$$ ($$$1\le b\le 3,b\ne a, 1\le i,j\le n$$$) —, что означает, что Боб кладет в ячейку $$$(i, j)$$$ фишку цвета $$$b$$$. Ячейка $$$(i, j)$$$ не должна содержать фишки из предыдущих ходов. Если ваш ход недействителен или проигрывает партию, взаимодействие прекратится и вы получите вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>После того как все $$$n^2$$$ ходов были сделаны, завершите программу, чтобы избежать неожиданных вердиктов.</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 100$$$).</p><p>Вторая строка содержит $$$n^2$$$ целых чисел $$$a_1,\ldots,a_{n^2}$$$ ($$$1\le a_i\le 3$$$), где $$$a_i$$$ обозначает цвет Алисы на $$$i$$$-м ходу игры.</p><p>Интерактор может отклониться от заданного во взломе порядка цветов, но только в том случае, если это заставит Боба проиграть.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 3 1 2 3 2 1 1 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Конечное состояние доски из примера изображено ниже. Боб выигрывает, потому что нет двух соседних ячеек с фишками одного и того же цвета. $$$$$$\begin{matrix}2&amp;3\\3&amp;1\end{matrix}$$$$$$</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:54</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bea47c717b73',t:'MTY5NjY2NzAzNC41NDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u0433\u0440\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1700"]
1503C
1503
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$$$, красота города $$$i$$$ равна $$$a_i$$$.</p><p>Коммивояжёр хочет начать с города $$$1$$$, посетить каждый город ровно один раз и вернуться в город $$$1$$$.</p><p>Для всех $$$i\ne j$$$, перелет из города $$$i$$$ в город $$$j$$$ стоит $$$\max(c_i,a_j-a_i)$$$ долларов, где $$$c_i$$$ — это нижний порог цены, наложенный на перелет городом $$$i$$$. Обратите внимание, что здесь не берется абсолютное значение. Найдите минимальную общую стоимость поездки для коммивояжёра.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое $$$n$$$ ($$$2\le n\le 10^5$$$) — количество городов.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится по два целых числа $$$a_i$$$, $$$c_i$$$ ($$$0\le a_i,c_i\le 10^9$$$) — красота и нижний порог цены города $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальную суммарную стоимость.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 9 2 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 2 8 4 3 0 2 3 7 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере мы можем путешествовать в порядке $$$1\to 3\to 2\to 1$$$. </p><ul> <li> Рейс $$$1\to 3$$$ стоит $$$\max(c_1,a_3-a_1)=\max(9,4-1)=9$$$. </li><li> Рейс $$$3\to 2$$$ стоит $$$\max(c_3, a_2-a_3)=\max(1,2-4)=1$$$. </li><li> Рейс $$$2\to 1$$$ стоит $$$\max(c_2,a_1-a_2)=\max(1,1-2)=1$$$. </li></ul><p>Общая стоимость составляет $$$11$$$, и мы не можем обойтись меньшим числом долларов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="8ead32d753e59f27610300db9fcb86aa"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="859c69031442a2c7b37200788e3a5d4f0a696bd0"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8ead32d753e59f27610300db9fcb86aa'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1503%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='8ead32d753e59f27610300db9fcb86aa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1503">Codeforces Round 712 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8ead32d753e59f27610300db9fcb86aa'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1503/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='8ead32d753e59f27610300db9fcb86aa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945471"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8ead32d753e59f27610300db9fcb86aa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945471"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13429" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13437" resourceName="T" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1503">Задачи</a></li> <li><a href="/contest/1503/submit">Отослать</a></li> <li><a href="/contest/1503/my">Мои посылки</a></li> <li><a href="/contest/1503/status">Статус</a></li> <li><a href="/contest/1503/hacks">Взломы</a></li> <li><a href="/contest/1503/room/1">Комната</a></li> <li><a href="/contest/1503/standings">Положение</a></li> <li><a href="/contest/1503/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_33fbf367b3eaaabb1e0e247644b703f7777b3eb3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$, красота города $$$i$$$ равна $$$a_i$$$.</p><p>Коммивояжёр хочет начать с города $$$1$$$, посетить каждый город ровно один раз и вернуться в город $$$1$$$.</p><p>Для всех $$$i\ne j$$$, перелет из города $$$i$$$ в город $$$j$$$ стоит $$$\max(c_i,a_j-a_i)$$$ долларов, где $$$c_i$$$ — это нижний порог цены, наложенный на перелет городом $$$i$$$. Обратите внимание, что здесь не берется абсолютное значение. Найдите минимальную общую стоимость поездки для коммивояжёра.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое $$$n$$$ ($$$2\le n\le 10^5$$$) — количество городов.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится по два целых числа $$$a_i$$$, $$$c_i$$$ ($$$0\le a_i,c_i\le 10^9$$$) — красота и нижний порог цены города $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальную суммарную стоимость.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 9 2 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 2 8 4 3 0 2 3 7 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере мы можем путешествовать в порядке $$$1\to 3\to 2\to 1$$$. </p><ul> <li> Рейс $$$1\to 3$$$ стоит $$$\max(c_1,a_3-a_1)=\max(9,4-1)=9$$$. </li><li> Рейс $$$3\to 2$$$ стоит $$$\max(c_3, a_2-a_3)=\max(1,2-4)=1$$$. </li><li> Рейс $$$2\to 1$$$ стоит $$$\max(c_2,a_1-a_2)=\max(1,1-2)=1$$$. </li></ul><p>Общая стоимость составляет $$$11$$$, и мы не можем обойтись меньшим числом долларов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:55</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bead9bb09d76',t:'MTY5NjY2NzAzNi4wMjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \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", "\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", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"]
1503D
1503
D
ru
D. Переверните карты
<div class="problem-statement"><div class="header"><div class="title">D. Переверните карты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть колода из $$$n$$$ карт. На карте $$$i$$$ на лицевой стороне написано число $$$a_i$$$, а на оборотной — $$$b_i$$$. Каждое целое число от $$$1$$$ до $$$2n$$$ встречается на картах ровно один раз.</p><p>Колода называется отсортированной, если лицевые значения находятся в порядке <span class="tex-font-style-bf">возрастания</span>, а оборотные — в порядке <span class="tex-font-style-bf">убывания</span>. То есть, если $$$a_i&lt; a_{i+1}$$$ и $$$b_i&gt; b_{i+1}$$$ для всех $$$1\le i&lt;n$$$.</p><p>Перевернуть карту $$$i$$$ означает поменять местами значения $$$a_i$$$ и $$$b_i$$$. Вы должны перевернуть некоторое подмножество карт (возможно, ни одной), а затем разместить эти карты в каком-то порядке. Какое минимальное количество карт вы должны перевернуть, чтобы отсортировать колоду?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — количество карт.</p><p>Следующие $$$n$$$ строк описывают карты. $$$i$$$-я из этих строк содержит два целых числа $$$a_i, b_i$$$ ($$$1\le a_i, b_i\le 2n$$$). Каждое целое число от $$$1$$$ до $$$2n$$$ встречается ровно один раз.</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> 5 3 10 6 4 1 9 5 8 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 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> 3 1 2 3 6 4 5 </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, 9)$$$ и $$$(2, 7)$$$. Затем карты располагают в порядке $$$(3,10), (5,8), (6,4), (7,2), (9,1)$$$. Колода отсортирована потому, что $$$3&lt;5&lt;6&lt;7&lt;9$$$ и $$$10&gt;8&gt;4&gt;2&gt;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="fe19156ce09994518e27fbe362e289c1"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="859c69031442a2c7b37200788e3a5d4f0a696bd0"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='fe19156ce09994518e27fbe362e289c1'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1503%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='fe19156ce09994518e27fbe362e289c1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1503">Codeforces Round 712 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='fe19156ce09994518e27fbe362e289c1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1503/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="2-SAT (2-satisfiability)"> 2-sat </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='fe19156ce09994518e27fbe362e289c1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945472"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fe19156ce09994518e27fbe362e289c1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945472"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13429" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13437" resourceName="T" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1503">Задачи</a></li> <li><a href="/contest/1503/submit">Отослать</a></li> <li><a href="/contest/1503/my">Мои посылки</a></li> <li><a href="/contest/1503/status">Статус</a></li> <li><a href="/contest/1503/hacks">Взломы</a></li> <li><a href="/contest/1503/room/1">Комната</a></li> <li><a href="/contest/1503/standings">Положение</a></li> <li><a href="/contest/1503/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9b0110c93f5883bc65d3e1fcb8a276b48a914aa2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Переверните карты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть колода из $$$n$$$ карт. На карте $$$i$$$ на лицевой стороне написано число $$$a_i$$$, а на оборотной — $$$b_i$$$. Каждое целое число от $$$1$$$ до $$$2n$$$ встречается на картах ровно один раз.</p><p>Колода называется отсортированной, если лицевые значения находятся в порядке <span class="tex-font-style-bf">возрастания</span>, а оборотные — в порядке <span class="tex-font-style-bf">убывания</span>. То есть, если $$$a_i&lt; a_{i+1}$$$ и $$$b_i&gt; b_{i+1}$$$ для всех $$$1\le i&lt;n$$$.</p><p>Перевернуть карту $$$i$$$ означает поменять местами значения $$$a_i$$$ и $$$b_i$$$. Вы должны перевернуть некоторое подмножество карт (возможно, ни одной), а затем разместить эти карты в каком-то порядке. Какое минимальное количество карт вы должны перевернуть, чтобы отсортировать колоду?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — количество карт.</p><p>Следующие $$$n$$$ строк описывают карты. $$$i$$$-я из этих строк содержит два целых числа $$$a_i, b_i$$$ ($$$1\le a_i, b_i\le 2n$$$). Каждое целое число от $$$1$$$ до $$$2n$$$ встречается ровно один раз.</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> 5 3 10 6 4 1 9 5 8 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 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> 3 1 2 3 6 4 5 </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, 9)$$$ и $$$(2, 7)$$$. Затем карты располагают в порядке $$$(3,10), (5,8), (6,4), (7,2), (9,1)$$$. Колода отсортирована потому, что $$$3&lt;5&lt;6&lt;7&lt;9$$$ и $$$10&gt;8&gt;4&gt;2&gt;1$$$.</p><p>Во втором примере отсортировать колоду невозможно.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:57</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124beb6cb1878ff',t:'MTY5NjY2NzAzNy4zNzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["2-SAT (2-satisfiability)", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\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"]
["2-sat", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"]
1503E
1503
E
ru
E. 2-раскраска
<div class="problem-statement"><div class="header"><div class="title">E. 2-раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана сетка с $$$n$$$ строками и $$$m$$$ столбцами. Каждая ячейка сетки должна быть окрашена в синий или желтый цвет.</p><p>Раскраска сетки называется глупой, если в каждой строке есть ровно один отрезок синих ячеек, а в каждом столбце — ровно один отрезок желтых ячеек.</p><p>Другими словами, каждая строка должна иметь хотя бы одну синюю ячейку, и все синие ячейки в строке должны быть последовательными. Точно так же каждый столбец должен иметь хотя бы одну желтую ячейку, а все желтые ячейки в столбце должны быть последовательными.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/269b01ee0ca84f0b74c1a7220d58280b61d115fe.png" style="max-width: 100.0%;max-height: 100.0%;"/> Пример глупой раскраски. </center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1898235ec8e6365798d3e59b27975ed7b774aaa4.png" style="max-width: 100.0%;max-height: 100.0%;"/> Примеры умных раскрасок. В первой раскраске отсутствует синяя ячейка во втором ряду, а во второй раскраске есть два желтых отрезка во втором столбце. </center><p>Сколько всего существует глупых раскрасок сетки? Две раскраски считаются различными, если есть какая-то ячейка, которая раскрашена в них в разные цвета.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа $$$n$$$, $$$m$$$ ($$$1\le n, m\le 2021$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — количество глупых раскрасок по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 294 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2020 2021 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 50657649 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера единственные две глупые раскраски $$$2\times 2$$$ изображены ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7faa5efe911c5dccfb095ae05af65d6a0980943a.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="1c3f0a056c35b43bc8c934f7c1d25c91"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="859c69031442a2c7b37200788e3a5d4f0a696bd0"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='1c3f0a056c35b43bc8c934f7c1d25c91'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1503%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='1c3f0a056c35b43bc8c934f7c1d25c91'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1503">Codeforces Round 712 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1c3f0a056c35b43bc8c934f7c1d25c91'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1503/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1c3f0a056c35b43bc8c934f7c1d25c91'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945473"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1c3f0a056c35b43bc8c934f7c1d25c91'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945473"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13429" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13437" resourceName="T" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1503">Задачи</a></li> <li><a href="/contest/1503/submit">Отослать</a></li> <li><a href="/contest/1503/my">Мои посылки</a></li> <li><a href="/contest/1503/status">Статус</a></li> <li><a href="/contest/1503/hacks">Взломы</a></li> <li><a href="/contest/1503/room/1">Комната</a></li> <li><a href="/contest/1503/standings">Положение</a></li> <li><a href="/contest/1503/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_84eb6f158b60e7e9f8e40816e29a55ce7a8c497c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. 2-раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана сетка с $$$n$$$ строками и $$$m$$$ столбцами. Каждая ячейка сетки должна быть окрашена в синий или желтый цвет.</p><p>Раскраска сетки называется глупой, если в каждой строке есть ровно один отрезок синих ячеек, а в каждом столбце — ровно один отрезок желтых ячеек.</p><p>Другими словами, каждая строка должна иметь хотя бы одну синюю ячейку, и все синие ячейки в строке должны быть последовательными. Точно так же каждый столбец должен иметь хотя бы одну желтую ячейку, а все желтые ячейки в столбце должны быть последовательными.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/269b01ee0ca84f0b74c1a7220d58280b61d115fe.png" style="max-width: 100.0%;max-height: 100.0%;" /> Пример глупой раскраски. </center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1898235ec8e6365798d3e59b27975ed7b774aaa4.png" style="max-width: 100.0%;max-height: 100.0%;" /> Примеры умных раскрасок. В первой раскраске отсутствует синяя ячейка во втором ряду, а во второй раскраске есть два желтых отрезка во втором столбце. </center><p>Сколько всего существует глупых раскрасок сетки? Две раскраски считаются различными, если есть какая-то ячейка, которая раскрашена в них в разные цвета.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа $$$n$$$, $$$m$$$ ($$$1\le n, m\le 2021$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — количество глупых раскрасок по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 294 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2020 2021 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 50657649 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера единственные две глупые раскраски $$$2\times 2$$$ изображены ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7faa5efe911c5dccfb095ae05af65d6a0980943a.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:23:58</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bebf9e0475b7',t:'MTY5NjY2NzAzOC43NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3100"]
1503F
1503
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><ul> <li> Пустая последовательность сбалансирована. </li><li> Если $$$[a_1,\ldots,a_n]$$$ и $$$[b_1,\ldots, b_m]$$$ сбалансированы, то их конкатенация $$$[a_1,\ldots,a_n,b_1,\ldots,b_m]$$$ сбалансирована. </li><li> Если $$$x$$$ — целое положительное число и $$$[a_1,\ldots,a_n]$$$ сбалансирована, то $$$[x,a_1,\ldots,a_n,-x]$$$ сбалансирована. </li></ul><p>Положительные числа можно представить себе в виде открывающихся скобок, а отрицательные — в виде закрывающих скобок, где соответствующие скобки должны иметь одинаковый тип (абсолютное значение). Например, $$$[1, 2, -2, -1]$$$ и $$$[1, 3, -3, 2, -2, -1]$$$ сбалансированы, но $$$[1, 2, -1, -2]$$$ и $$$[-1, 1]$$$ не сбалансированы.</p><p>Есть $$$2n$$$ карт. Каждая карта имеет число на лицевой стороне и число на оборотной. Каждое целое число $$$1,-1,2,-2,\ldots,n,-n$$$ встречается на лицевой стороне ровно одной карты и на оборотной стороне ровной одной карты (необязательно той же карты).</p><p>Вы можете переупорядочить карты, как вам угодно. Вам <span class="tex-font-style-bf">не</span> разрешено переворачивать карты, поэтому числа не могут перемещаться между лицевой и оборотной сторонами карты. Ваша задача — упорядочить карты так, чтобы последовательности, заданные числами на лицевых и оборотных сторонах, были сбалансированы, или сообщить, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — количество типов скобок и половина количества карт.</p><p>Следующие $$$2n$$$ строк описывают карты. В $$$i$$$-й из этих строк содержатся два целых числа $$$a_i$$$, $$$b_i$$$ ($$$-n\le a_i,b_i\le n$$$, $$$a_i\ne 0$$$, $$$b_i\ne 0$$$) — числа на лицевой и оборотной стороне $$$i$$$-й карты соответственно. Каждое целое число $$$1,-1,2,-2,\ldots,n,-n$$$ встречается ровно один раз как $$$a_i$$$ и ровно один раз как $$$b_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>Если это возможно, в следующих $$$2n$$$ строках выведите карты в таком порядке, чтобы и лицевая и оборотная части были сбалансированы. Если есть несколько решений, то можно вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 -3 -5 4 -3 2 2 -1 -4 -2 5 3 -1 5 1 -4 4 -5 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 3 4 -3 -4 4 -1 -4 5 1 3 -1 2 2 -2 5 -3 -5 -5 -2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 -1 2 2 -1 -2 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере лицевые числа образуют сбалансированную последовательность $$$[1,4,-4,-1,5,3,2,-2,-3,-5]$$$, а оборотные числа создают сбалансированную последовательность $$$[3,-3,4,-4,1,-1,2,5,-5,-2]$$$.</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="bfb1e66b5debc11285d27a59c7f63485"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="859c69031442a2c7b37200788e3a5d4f0a696bd0"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='bfb1e66b5debc11285d27a59c7f63485'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1503%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='bfb1e66b5debc11285d27a59c7f63485'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1503">Codeforces Round 712 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='bfb1e66b5debc11285d27a59c7f63485'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1503/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Геометрия"> геометрия </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='bfb1e66b5debc11285d27a59c7f63485'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945474"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bfb1e66b5debc11285d27a59c7f63485'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945474"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13429" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="T" target="_blank">T <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13437" resourceName="T" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1503">Задачи</a></li> <li><a href="/contest/1503/submit">Отослать</a></li> <li><a href="/contest/1503/my">Мои посылки</a></li> <li><a href="/contest/1503/status">Статус</a></li> <li><a href="/contest/1503/hacks">Взломы</a></li> <li><a href="/contest/1503/room/1">Комната</a></li> <li><a href="/contest/1503/standings">Положение</a></li> <li><a href="/contest/1503/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e862d6182cb4e66721a73516927da3141b9589f5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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><ul> <li> Пустая последовательность сбалансирована. </li><li> Если $$$[a_1,\ldots,a_n]$$$ и $$$[b_1,\ldots, b_m]$$$ сбалансированы, то их конкатенация $$$[a_1,\ldots,a_n,b_1,\ldots,b_m]$$$ сбалансирована. </li><li> Если $$$x$$$ — целое положительное число и $$$[a_1,\ldots,a_n]$$$ сбалансирована, то $$$[x,a_1,\ldots,a_n,-x]$$$ сбалансирована. </li></ul><p>Положительные числа можно представить себе в виде открывающихся скобок, а отрицательные — в виде закрывающих скобок, где соответствующие скобки должны иметь одинаковый тип (абсолютное значение). Например, $$$[1, 2, -2, -1]$$$ и $$$[1, 3, -3, 2, -2, -1]$$$ сбалансированы, но $$$[1, 2, -1, -2]$$$ и $$$[-1, 1]$$$ не сбалансированы.</p><p>Есть $$$2n$$$ карт. Каждая карта имеет число на лицевой стороне и число на оборотной. Каждое целое число $$$1,-1,2,-2,\ldots,n,-n$$$ встречается на лицевой стороне ровно одной карты и на оборотной стороне ровной одной карты (необязательно той же карты).</p><p>Вы можете переупорядочить карты, как вам угодно. Вам <span class="tex-font-style-bf">не</span> разрешено переворачивать карты, поэтому числа не могут перемещаться между лицевой и оборотной сторонами карты. Ваша задача — упорядочить карты так, чтобы последовательности, заданные числами на лицевых и оборотных сторонах, были сбалансированы, или сообщить, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — количество типов скобок и половина количества карт.</p><p>Следующие $$$2n$$$ строк описывают карты. В $$$i$$$-й из этих строк содержатся два целых числа $$$a_i$$$, $$$b_i$$$ ($$$-n\le a_i,b_i\le n$$$, $$$a_i\ne 0$$$, $$$b_i\ne 0$$$) — числа на лицевой и оборотной стороне $$$i$$$-й карты соответственно. Каждое целое число $$$1,-1,2,-2,\ldots,n,-n$$$ встречается ровно один раз как $$$a_i$$$ и ровно один раз как $$$b_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>Если это возможно, в следующих $$$2n$$$ строках выведите карты в таком порядке, чтобы и лицевая и оборотная части были сбалансированы. Если есть несколько решений, то можно вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 -3 -5 4 -3 2 2 -1 -4 -2 5 3 -1 5 1 -4 4 -5 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 1 3 4 -3 -4 4 -1 -4 5 1 3 -1 2 2 -2 5 -3 -5 -5 -2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 -1 2 2 -1 -2 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере лицевые числа образуют сбалансированную последовательность $$$[1,4,-4,-1,5,3,2,-2,-3,-5]$$$, а оборотные числа создают сбалансированную последовательность $$$[3,-3,4,-4,1,-1,2,5,-5,-2]$$$.</p><p>Во втором примере карты даются в таком порядке, что лицевые числа сбалансированы, а оборотные образуют несбалансированную последовательность $$$[1,2,-1,-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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:00</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bec80cbb9d73',t:'MTY5NjY2NzA0MC4zNjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0433\u0440\u0430\u0444\u044b", "\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", "\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", "*3500"]
1504A
1504
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-tt">z</span>», «<span class="tex-font-style-tt">aa</span>», «<span class="tex-font-style-tt">aba</span>» и «<span class="tex-font-style-tt">abccba</span>» — палиндромы, а «<span class="tex-font-style-tt">codeforces</span>» и «<span class="tex-font-style-tt">ab</span>» — нет. Вы ненавидите палиндромы, потому что они вызывают у вас <span class="tex-font-style-it">дежавю</span>.</p><p>Дана строка $$$s$$$. Вы <span class="tex-font-style-bf">должны</span> вставить <span class="tex-font-style-bf">ровно один</span> символ '<span class="tex-font-style-tt">a</span>' в $$$s$$$. Если таким образом можно получить строку, которая <span class="tex-font-style-bf">не</span> является палиндромом, вам нужно найти одну из них. В противном случае следует сообщить, что это невозможно.</p><p>Например, предположим, что $$$s=$$$ «<span class="tex-font-style-tt">cbabc</span>». Вставив '<span class="tex-font-style-tt">a</span>', можно получить «<span class="tex-font-style-tt">acbabc</span>», «<span class="tex-font-style-tt">cababc</span>», «<span class="tex-font-style-tt">cbaabc</span>», «<span class="tex-font-style-tt">cbabac</span>», или «<span class="tex-font-style-tt">cbabca</span>». Строка «<span class="tex-font-style-tt">cbaabc</span>» — палиндром, и не подходит, поэтому вы должны вывести другую из вышеперечисленных строк.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит строку $$$s$$$, состоящую из строчных английских букв.</p><p>Суммарная длина всех строк не превышает $$$3\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если нет решения, выведите «<span class="tex-font-style-tt">NO</span>».</p><p>В противном случае выведите «<span class="tex-font-style-tt">YES</span>», а в следующей строке выведите строку длиной $$$|s|+1$$$. Если есть несколько решений, можно вывести любое из них.</p><p>Вы можете выводить каждый символ «<span class="tex-font-style-tt">YES</span>» и «<span class="tex-font-style-tt">NO</span>» в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 cbabc ab zza ba a nutforajaroftuna </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES cbabac YES aab YES zaza YES baa NO YES nutforajarofatuna </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор входных данных описан в условии.</p><p>Во втором наборе входных данных можно получить либо «<span class="tex-font-style-tt">aab</span>», либо «<span class="tex-font-style-tt">aba</span>». Но «<span class="tex-font-style-tt">aba</span>» — это палиндром, поэтому «<span class="tex-font-style-tt">aab</span>» — единственный правильный ответ.</p><p>В третьем наборе входных данных «<span class="tex-font-style-tt">zaza</span>» и «<span class="tex-font-style-tt">zzaa</span>» — правильные ответы, а «<span class="tex-font-style-tt">azza</span>» — нет.</p><p>В четвертом наборе входных данных «<span class="tex-font-style-tt">baa</span>» — единственный правильный ответ.</p><p>В пятом наборе входных данных мы можем получить только «<span class="tex-font-style-tt">aa</span>», что является палиндромом. Следовательно, ответ «<span class="tex-font-style-tt">NO</span>».</p><p>В шестом наборе входных данных «<span class="tex-font-style-tt">anutforajaroftuna</span>» — палиндром, но вставка '<span class="tex-font-style-tt">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="a88aa83e4f768b8ee5a80985680d5343"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="23fb4b555d0b12580ceb2f448033070f43802043"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a88aa83e4f768b8ee5a80985680d5343'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1504%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='a88aa83e4f768b8ee5a80985680d5343'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1504">Codeforces Round 712 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a88aa83e4f768b8ee5a80985680d5343'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1504/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='a88aa83e4f768b8ee5a80985680d5343'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945463"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a88aa83e4f768b8ee5a80985680d5343'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945463"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13430" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="Codeforces Round #712 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13445" resourceName="Codeforces Round #712 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1504">Задачи</a></li> <li><a href="/contest/1504/submit">Отослать</a></li> <li><a href="/contest/1504/my">Мои посылки</a></li> <li><a href="/contest/1504/status">Статус</a></li> <li><a href="/contest/1504/hacks">Взломы</a></li> <li><a href="/contest/1504/room/1">Комната</a></li> <li><a href="/contest/1504/standings">Положение</a></li> <li><a href="/contest/1504/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2604cfd1c8b0bbfda68b9c2a51a267cb3498e694"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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-tt">z</span>», «<span class="tex-font-style-tt">aa</span>», «<span class="tex-font-style-tt">aba</span>» и «<span class="tex-font-style-tt">abccba</span>» — палиндромы, а «<span class="tex-font-style-tt">codeforces</span>» и «<span class="tex-font-style-tt">ab</span>» — нет. Вы ненавидите палиндромы, потому что они вызывают у вас <span class="tex-font-style-it">дежавю</span>.</p><p>Дана строка $$$s$$$. Вы <span class="tex-font-style-bf">должны</span> вставить <span class="tex-font-style-bf">ровно один</span> символ '<span class="tex-font-style-tt">a</span>' в $$$s$$$. Если таким образом можно получить строку, которая <span class="tex-font-style-bf">не</span> является палиндромом, вам нужно найти одну из них. В противном случае следует сообщить, что это невозможно.</p><p>Например, предположим, что $$$s=$$$ «<span class="tex-font-style-tt">cbabc</span>». Вставив '<span class="tex-font-style-tt">a</span>', можно получить «<span class="tex-font-style-tt">acbabc</span>», «<span class="tex-font-style-tt">cababc</span>», «<span class="tex-font-style-tt">cbaabc</span>», «<span class="tex-font-style-tt">cbabac</span>», или «<span class="tex-font-style-tt">cbabca</span>». Строка «<span class="tex-font-style-tt">cbaabc</span>» — палиндром, и не подходит, поэтому вы должны вывести другую из вышеперечисленных строк.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит строку $$$s$$$, состоящую из строчных английских букв.</p><p>Суммарная длина всех строк не превышает $$$3\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если нет решения, выведите «<span class="tex-font-style-tt">NO</span>».</p><p>В противном случае выведите «<span class="tex-font-style-tt">YES</span>», а в следующей строке выведите строку длиной $$$|s|+1$$$. Если есть несколько решений, можно вывести любое из них.</p><p>Вы можете выводить каждый символ «<span class="tex-font-style-tt">YES</span>» и «<span class="tex-font-style-tt">NO</span>» в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 cbabc ab zza ba a nutforajaroftuna </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES cbabac YES aab YES zaza YES baa NO YES nutforajarofatuna </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор входных данных описан в условии.</p><p>Во втором наборе входных данных можно получить либо «<span class="tex-font-style-tt">aab</span>», либо «<span class="tex-font-style-tt">aba</span>». Но «<span class="tex-font-style-tt">aba</span>» — это палиндром, поэтому «<span class="tex-font-style-tt">aab</span>» — единственный правильный ответ.</p><p>В третьем наборе входных данных «<span class="tex-font-style-tt">zaza</span>» и «<span class="tex-font-style-tt">zzaa</span>» — правильные ответы, а «<span class="tex-font-style-tt">azza</span>» — нет.</p><p>В четвертом наборе входных данных «<span class="tex-font-style-tt">baa</span>» — единственный правильный ответ.</p><p>В пятом наборе входных данных мы можем получить только «<span class="tex-font-style-tt">aa</span>», что является палиндромом. Следовательно, ответ «<span class="tex-font-style-tt">NO</span>».</p><p>В шестом наборе входных данных «<span class="tex-font-style-tt">anutforajaroftuna</span>» — палиндром, но вставка '<span class="tex-font-style-tt">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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:01</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bed1eaa375af',t:'MTY5NjY2NzA0MS44MDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"]
1504B
1504
B
ru
B. Меняем биты
<div class="problem-statement"><div class="header"><div class="title">B. Меняем биты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана бинарная строка $$$a$$$ длины $$$n$$$. За одну операцию можно выбрать любой префикс $$$a$$$ с <span class="tex-font-style-bf">равным</span> числом символов $$$0$$$ и $$$1$$$. Затем все символы в префиксе меняются: каждый $$$0$$$ становится $$$1$$$, а каждый $$$1$$$ — $$$0$$$.</p><p>Например, предположим, что $$$a=0111010000$$$. </p><ul> <li> В первой операции можно выбрать префикс длины $$$8$$$, так как он имеет четыре $$$0$$$ и четыре $$$1$$$: $$$[01110100]00\to [10001011]00$$$. </li><li> Во второй операции можно выбрать префикс длины $$$2$$$, так как он имеет один $$$0$$$ и одну $$$1$$$: $$$[10]00101100\to [01]00101100$$$. </li><li> Для третьей операции запрещено выбирать префикс длины $$$4$$$, так как он имеет три $$$0$$$ и одну $$$1$$$. </li></ul><p>Можете ли вы преобразовать строку $$$a$$$ в строку $$$b$$$, сделав некоторое конечное количество операций (возможно, ни одной)?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$) — длина строк $$$a$$$ и $$$b$$$.</p><p>Следующие две строки содержат строки $$$a$$$ и $$$b$$$ длиной $$$n$$$, состоящие из символов $$$0$$$ и $$$1$$$.</p><p>Сумма $$$n$$$ во всех наборах входных данных не превышает $$$3\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>», если возможно преобразовать $$$a$$$ в $$$b$$$, или «<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 10 0111010000 0100101100 4 0000 0000 3 001 000 12 010101010101 100110011010 6 000111 110100 </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>Первый набор входных данных разобран в условии.</p><p>Во втором наборе входных данных мы преобразуем $$$a$$$ в $$$b$$$, используя ноль операций.</p><p>В третьем наборе входных данных нельзя сделать ни одну операцию, поэтому преобразовать $$$a$$$ в $$$b$$$ невозможно.</p><p>В четвертом наборе входных данных, вот одно из таких преобразований: </p><ul> <li> Выберите префикс длины $$$2$$$, чтобы получить $$$100101010101$$$. </li><li> Выберите префикс длины $$$12$$$, чтобы получить $$$011010101010$$$. </li><li> Выберите префикс длины $$$8$$$, чтобы получить $$$100101011010$$$. </li><li> Выберите префикс длины $$$4$$$, чтобы получить $$$011001011010$$$. </li><li> Выберите префикс длины $$$6$$$, чтобы получить $$$100110011010$$$. </li></ul><p>В пятом наборе входных данных единственной разрешенной операцией является преобразование $$$a$$$ в $$$111000$$$. Но для получившейся строки единственная разрешенная операция — это вернуться к строке, с которой мы начали, поэтому мы не можем преобразовать $$$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="c9b4ab1870ec77d8db1813d9ab451f93"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="23fb4b555d0b12580ceb2f448033070f43802043"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c9b4ab1870ec77d8db1813d9ab451f93'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1504%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='c9b4ab1870ec77d8db1813d9ab451f93'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1504">Codeforces Round 712 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='c9b4ab1870ec77d8db1813d9ab451f93'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1504/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='c9b4ab1870ec77d8db1813d9ab451f93'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945464"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c9b4ab1870ec77d8db1813d9ab451f93'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945464"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13430" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="Codeforces Round #712 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13445" resourceName="Codeforces Round #712 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1504">Задачи</a></li> <li><a href="/contest/1504/submit">Отослать</a></li> <li><a href="/contest/1504/my">Мои посылки</a></li> <li><a href="/contest/1504/status">Статус</a></li> <li><a href="/contest/1504/hacks">Взломы</a></li> <li><a href="/contest/1504/room/1">Комната</a></li> <li><a href="/contest/1504/standings">Положение</a></li> <li><a href="/contest/1504/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_05910f3259a72b1aa97547fd9f84ae48b544c025"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Меняем биты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана бинарная строка $$$a$$$ длины $$$n$$$. За одну операцию можно выбрать любой префикс $$$a$$$ с <span class="tex-font-style-bf">равным</span> числом символов $$$0$$$ и $$$1$$$. Затем все символы в префиксе меняются: каждый $$$0$$$ становится $$$1$$$, а каждый $$$1$$$ — $$$0$$$.</p><p>Например, предположим, что $$$a=0111010000$$$. </p><ul> <li> В первой операции можно выбрать префикс длины $$$8$$$, так как он имеет четыре $$$0$$$ и четыре $$$1$$$: $$$[01110100]00\to [10001011]00$$$. </li><li> Во второй операции можно выбрать префикс длины $$$2$$$, так как он имеет один $$$0$$$ и одну $$$1$$$: $$$[10]00101100\to [01]00101100$$$. </li><li> Для третьей операции запрещено выбирать префикс длины $$$4$$$, так как он имеет три $$$0$$$ и одну $$$1$$$. </li></ul><p>Можете ли вы преобразовать строку $$$a$$$ в строку $$$b$$$, сделав некоторое конечное количество операций (возможно, ни одной)?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$) — длина строк $$$a$$$ и $$$b$$$.</p><p>Следующие две строки содержат строки $$$a$$$ и $$$b$$$ длиной $$$n$$$, состоящие из символов $$$0$$$ и $$$1$$$.</p><p>Сумма $$$n$$$ во всех наборах входных данных не превышает $$$3\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>», если возможно преобразовать $$$a$$$ в $$$b$$$, или «<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 10 0111010000 0100101100 4 0000 0000 3 001 000 12 010101010101 100110011010 6 000111 110100 </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>Первый набор входных данных разобран в условии.</p><p>Во втором наборе входных данных мы преобразуем $$$a$$$ в $$$b$$$, используя ноль операций.</p><p>В третьем наборе входных данных нельзя сделать ни одну операцию, поэтому преобразовать $$$a$$$ в $$$b$$$ невозможно.</p><p>В четвертом наборе входных данных, вот одно из таких преобразований: </p><ul> <li> Выберите префикс длины $$$2$$$, чтобы получить $$$100101010101$$$. </li><li> Выберите префикс длины $$$12$$$, чтобы получить $$$011010101010$$$. </li><li> Выберите префикс длины $$$8$$$, чтобы получить $$$100101011010$$$. </li><li> Выберите префикс длины $$$4$$$, чтобы получить $$$011001011010$$$. </li><li> Выберите префикс длины $$$6$$$, чтобы получить $$$100110011010$$$. </li></ul><p>В пятом наборе входных данных единственной разрешенной операцией является преобразование $$$a$$$ в $$$111000$$$. Но для получившейся строки единственная разрешенная операция — это вернуться к строке, с которой мы начали, поэтому мы не можем преобразовать $$$a$$$ в $$$b$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:03</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bedc1d0c76ad',t:'MTY5NjY2NzA0My4zNzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"]
1504C
1504
C
ru
C. Сбалансируйте биты
<div class="problem-statement"><div class="header"><div class="title">C. Сбалансируйте биты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Скобочная последовательность называется сбалансированной, если ее можно превратить в корректное математическое выражение путем добавления символов '<span class="tex-font-style-tt">+</span>' и '<span class="tex-font-style-tt">1</span>'. Например, последовательности «<span class="tex-font-style-tt">(())()</span>», «<span class="tex-font-style-tt">()</span>» и «<span class="tex-font-style-tt">(()(()))</span>» являются сбалансированными, а «<span class="tex-font-style-tt">)(</span>», «<span class="tex-font-style-tt">(()</span>» и «<span class="tex-font-style-tt">(()))(</span>» — нет.</p><p>Вам дана бинарная строка $$$s$$$ длины $$$n$$$. Постройте две сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$ длины $$$n$$$ такие, что для всех $$$1\le i\le n$$$ выполняется: </p><ul> <li> если $$$s_i=1$$$, то $$$a_i=b_i$$$ </li><li> если $$$s_i=0$$$, то $$$a_i\ne b_i$$$ </li></ul><p>Если это невозможно, вы должны это определить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое число $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ — четное).</p><p>Следующая строка содержит строку $$$s$$$ длины $$$n$$$, состоящую из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Сумма $$$n$$$ во всех тестовых случаях не превышает $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если такие две сбалансированные скобочные последовательности существуют, выведите «<span class="tex-font-style-tt">YES</span>» в первой строке, иначе выведите «<span class="tex-font-style-tt">NO</span>». Вы можете выводить каждый символ в любом регистре.</p><p>Если ответ «<span class="tex-font-style-tt">YES</span>», в двух следующих строках выведите сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$, удовлетворяющие условиям.</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 6 101101 10 1001101101 4 1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES ()()() ((())) YES ()()((())) (())()()() NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()()</span>» и $$$b=$$$«<span class="tex-font-style-tt">((()))</span>». Символы равны в позициях $$$1$$$, $$$3$$$, $$$4$$$ и $$$6$$$, ровно в тех позициях, где $$$s_i=1$$$.</p><p>Во втором наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()((()))</span>» и $$$b=$$$«<span class="tex-font-style-tt">(())()()()</span>». Символы равны в позициях $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, ровно в тех позициях, где $$$s_i=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="029d257617b654a0329f4adc84307be9"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="23fb4b555d0b12580ceb2f448033070f43802043"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='029d257617b654a0329f4adc84307be9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1504%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='029d257617b654a0329f4adc84307be9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1504">Codeforces Round 712 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='029d257617b654a0329f4adc84307be9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1504/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='029d257617b654a0329f4adc84307be9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945465"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='029d257617b654a0329f4adc84307be9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945465"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13430" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="Codeforces Round #712 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13445" resourceName="Codeforces Round #712 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1504">Задачи</a></li> <li><a href="/contest/1504/submit">Отослать</a></li> <li><a href="/contest/1504/my">Мои посылки</a></li> <li><a href="/contest/1504/status">Статус</a></li> <li><a href="/contest/1504/hacks">Взломы</a></li> <li><a href="/contest/1504/room/1">Комната</a></li> <li><a href="/contest/1504/standings">Положение</a></li> <li><a href="/contest/1504/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_43880d7c4dc0a9469e14a0a7da8e75b7496f30c3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Сбалансируйте биты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Скобочная последовательность называется сбалансированной, если ее можно превратить в корректное математическое выражение путем добавления символов '<span class="tex-font-style-tt">+</span>' и '<span class="tex-font-style-tt">1</span>'. Например, последовательности «<span class="tex-font-style-tt">(())()</span>», «<span class="tex-font-style-tt">()</span>» и «<span class="tex-font-style-tt">(()(()))</span>» являются сбалансированными, а «<span class="tex-font-style-tt">)(</span>», «<span class="tex-font-style-tt">(()</span>» и «<span class="tex-font-style-tt">(()))(</span>» — нет.</p><p>Вам дана бинарная строка $$$s$$$ длины $$$n$$$. Постройте две сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$ длины $$$n$$$ такие, что для всех $$$1\le i\le n$$$ выполняется: </p><ul> <li> если $$$s_i=1$$$, то $$$a_i=b_i$$$ </li><li> если $$$s_i=0$$$, то $$$a_i\ne b_i$$$ </li></ul><p>Если это невозможно, вы должны это определить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое число $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ — четное).</p><p>Следующая строка содержит строку $$$s$$$ длины $$$n$$$, состоящую из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Сумма $$$n$$$ во всех тестовых случаях не превышает $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если такие две сбалансированные скобочные последовательности существуют, выведите «<span class="tex-font-style-tt">YES</span>» в первой строке, иначе выведите «<span class="tex-font-style-tt">NO</span>». Вы можете выводить каждый символ в любом регистре.</p><p>Если ответ «<span class="tex-font-style-tt">YES</span>», в двух следующих строках выведите сбалансированные скобочные последовательности $$$a$$$ и $$$b$$$, удовлетворяющие условиям.</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 6 101101 10 1001101101 4 1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES ()()() ((())) YES ()()((())) (())()()() NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()()</span>» и $$$b=$$$«<span class="tex-font-style-tt">((()))</span>». Символы равны в позициях $$$1$$$, $$$3$$$, $$$4$$$ и $$$6$$$, ровно в тех позициях, где $$$s_i=1$$$.</p><p>Во втором наборе входных данных $$$a=$$$«<span class="tex-font-style-tt">()()((()))</span>» и $$$b=$$$«<span class="tex-font-style-tt">(())()()()</span>». Символы равны в позициях $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, ровно в тех позициях, где $$$s_i=1$$$.</p><p>В третьем наборе входных данных решения нет.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:04</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bee4cbcd1622',t:'MTY5NjY2NzA0NC42NjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1504D
1504
D
ru
D. 3-раскраска
<div class="problem-statement"><div class="header"><div class="title">D. 3-раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Алиса и Боб играют в игру. Есть доска $$$n\times n$$$, изначально пустая. Мы будем обозначать ячейку в строке $$$i$$$ и столбце $$$j$$$ как $$$(i, j)$$$ для $$$1\le i, j\le n$$$. Также, есть бесконечный запас фишек $$$3$$$ цветов, обозначенных $$$1$$$, $$$2$$$ и $$$3$$$.</p><p>Алиса и Боб ходят по очереди по следующим правилам: каждый ход начинается с того, что Алиса называет один из трех цветов, назовем его $$$a$$$. Затем Боб выбирает цвет $$$b\ne a$$$, выбирает пустую ячейку и помещает на нее фишку цвета $$$b$$$.</p><p>Мы говорим, что случился <span class="tex-font-style-bf">конфликт</span>, если есть две соседние ячейки, содержащие фишки одного цвета. Две ячейки считаются соседними, если у них есть общая сторона.</p><p>Если в какой-то момент возникает конфликт, Алиса побеждает. В противном случае, если было совершено $$$n^2$$$ ходов (так что доска полностью заполнилась) без конфликтов, побеждает Боб.</p><p>У нас есть доказательство того, что у Боба есть выигрышная стратегия. Сыграйте в игру за Боба и выиграйте.</p><p>Интерактор <span class="tex-font-style-bf">адаптивен</span>. Таким образом, выбор цвета Алисой может зависеть от предыдущих ходов Боба.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с чтения единственного целого числа $$$n$$$ ($$$2\le n\le 100$$$) — размера доски.</p><p>Дальше начинаются ходы. Каждый ход следует начинать с чтения целого $$$a$$$ ($$$1\le a\le 3$$$) — выбранного цвета Алисы.</p><p>Затем необходимо вывести три целых числа $$$b,i,j$$$ ($$$1\le b\le 3,b\ne a, 1\le i,j\le n$$$) —, что означает, что Боб кладет в ячейку $$$(i, j)$$$ фишку цвета $$$b$$$. Ячейка $$$(i, j)$$$ не должна содержать фишки из предыдущих ходов. Если ваш ход недействителен или проигрывает партию, взаимодействие прекратится и вы получите вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>После того как все $$$n^2$$$ ходов были сделаны, завершите программу, чтобы избежать неожиданных вердиктов.</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 100$$$).</p><p>Вторая строка содержит $$$n^2$$$ целых чисел $$$a_1,\ldots,a_{n^2}$$$ ($$$1\le a_i\le 3$$$), где $$$a_i$$$ обозначает цвет Алисы на $$$i$$$-м ходу игры.</p><p>Интерактор может отклониться от заданного во взломе порядка цветов, но только в том случае, если это заставит Боба проиграть.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 3 1 2 3 2 1 1 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Конечное состояние доски из примера изображено ниже. Боб выигрывает, потому что нет двух соседних ячеек с фишками одного и того же цвета. $$$$$$\begin{matrix}2&amp;3\\3&amp;1\end{matrix}$$$$$$</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="e79a4f16dba2a649f2f90476ec8cae3e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="23fb4b555d0b12580ceb2f448033070f43802043"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e79a4f16dba2a649f2f90476ec8cae3e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1504%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='e79a4f16dba2a649f2f90476ec8cae3e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1504">Codeforces Round 712 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e79a4f16dba2a649f2f90476ec8cae3e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1504/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди"> игры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='e79a4f16dba2a649f2f90476ec8cae3e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945466"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e79a4f16dba2a649f2f90476ec8cae3e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945466"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13430" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="Codeforces Round #712 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13445" resourceName="Codeforces Round #712 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1504">Задачи</a></li> <li><a href="/contest/1504/submit">Отослать</a></li> <li><a href="/contest/1504/my">Мои посылки</a></li> <li><a href="/contest/1504/status">Статус</a></li> <li><a href="/contest/1504/hacks">Взломы</a></li> <li><a href="/contest/1504/room/1">Комната</a></li> <li><a href="/contest/1504/standings">Положение</a></li> <li><a href="/contest/1504/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f30a9870d10be0cc282b6433d918cc1285b054e2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. 3-раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Алиса и Боб играют в игру. Есть доска $$$n\times n$$$, изначально пустая. Мы будем обозначать ячейку в строке $$$i$$$ и столбце $$$j$$$ как $$$(i, j)$$$ для $$$1\le i, j\le n$$$. Также, есть бесконечный запас фишек $$$3$$$ цветов, обозначенных $$$1$$$, $$$2$$$ и $$$3$$$.</p><p>Алиса и Боб ходят по очереди по следующим правилам: каждый ход начинается с того, что Алиса называет один из трех цветов, назовем его $$$a$$$. Затем Боб выбирает цвет $$$b\ne a$$$, выбирает пустую ячейку и помещает на нее фишку цвета $$$b$$$.</p><p>Мы говорим, что случился <span class="tex-font-style-bf">конфликт</span>, если есть две соседние ячейки, содержащие фишки одного цвета. Две ячейки считаются соседними, если у них есть общая сторона.</p><p>Если в какой-то момент возникает конфликт, Алиса побеждает. В противном случае, если было совершено $$$n^2$$$ ходов (так что доска полностью заполнилась) без конфликтов, побеждает Боб.</p><p>У нас есть доказательство того, что у Боба есть выигрышная стратегия. Сыграйте в игру за Боба и выиграйте.</p><p>Интерактор <span class="tex-font-style-bf">адаптивен</span>. Таким образом, выбор цвета Алисой может зависеть от предыдущих ходов Боба.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с чтения единственного целого числа $$$n$$$ ($$$2\le n\le 100$$$) — размера доски.</p><p>Дальше начинаются ходы. Каждый ход следует начинать с чтения целого $$$a$$$ ($$$1\le a\le 3$$$) — выбранного цвета Алисы.</p><p>Затем необходимо вывести три целых числа $$$b,i,j$$$ ($$$1\le b\le 3,b\ne a, 1\le i,j\le n$$$) —, что означает, что Боб кладет в ячейку $$$(i, j)$$$ фишку цвета $$$b$$$. Ячейка $$$(i, j)$$$ не должна содержать фишки из предыдущих ходов. Если ваш ход недействителен или проигрывает партию, взаимодействие прекратится и вы получите вердикт <span class="tex-font-style-bf">Неправильный ответ</span>.</p><p>После того как все $$$n^2$$$ ходов были сделаны, завершите программу, чтобы избежать неожиданных вердиктов.</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 100$$$).</p><p>Вторая строка содержит $$$n^2$$$ целых чисел $$$a_1,\ldots,a_{n^2}$$$ ($$$1\le a_i\le 3$$$), где $$$a_i$$$ обозначает цвет Алисы на $$$i$$$-м ходу игры.</p><p>Интерактор может отклониться от заданного во взломе порядка цветов, но только в том случае, если это заставит Боба проиграть.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 3 1 2 3 2 1 1 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Конечное состояние доски из примера изображено ниже. Боб выигрывает, потому что нет двух соседних ячеек с фишками одного и того же цвета. $$$$$$\begin{matrix}2&amp;3\\3&amp;1\end{matrix}$$$$$$</p><p>Пример приведен только для демонстрации входного и выходного формата. Не гарантируется, что он будет представлять оптимальную стратегию для Боба или реальное поведение интерактора.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:05</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124beecde039d76',t:'MTY5NjY2NzA0NS45NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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", "\u0438\u0433\u0440\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1700"]
1504E
1504
E
ru
E. Задача коммивояжёра
<div class="problem-statement"><div class="header"><div class="title">E. Задача коммивояжёра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть $$$n$$$ городов, пронумерованных от $$$1$$$ до $$$n$$$, красота города $$$i$$$ равна $$$a_i$$$.</p><p>Коммивояжёр хочет начать с города $$$1$$$, посетить каждый город ровно один раз и вернуться в город $$$1$$$.</p><p>Для всех $$$i\ne j$$$, перелет из города $$$i$$$ в город $$$j$$$ стоит $$$\max(c_i,a_j-a_i)$$$ долларов, где $$$c_i$$$ — это нижний порог цены, наложенный на перелет городом $$$i$$$. Обратите внимание, что здесь не берется абсолютное значение. Найдите минимальную общую стоимость поездки для коммивояжёра.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое $$$n$$$ ($$$2\le n\le 10^5$$$) — количество городов.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится по два целых числа $$$a_i$$$, $$$c_i$$$ ($$$0\le a_i,c_i\le 10^9$$$) — красота и нижний порог цены города $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальную суммарную стоимость.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 9 2 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 2 8 4 3 0 2 3 7 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере мы можем путешествовать в порядке $$$1\to 3\to 2\to 1$$$. </p><ul> <li> Рейс $$$1\to 3$$$ стоит $$$\max(c_1,a_3-a_1)=\max(9,4-1)=9$$$. </li><li> Рейс $$$3\to 2$$$ стоит $$$\max(c_3, a_2-a_3)=\max(1,2-4)=1$$$. </li><li> Рейс $$$2\to 1$$$ стоит $$$\max(c_2,a_1-a_2)=\max(1,1-2)=1$$$. </li></ul><p>Общая стоимость составляет $$$11$$$, и мы не можем обойтись меньшим числом долларов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="51feabdfeaea71ec5360d7c9d1b9deac"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="23fb4b555d0b12580ceb2f448033070f43802043"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='51feabdfeaea71ec5360d7c9d1b9deac'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1504%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='51feabdfeaea71ec5360d7c9d1b9deac'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1504">Codeforces Round 712 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='51feabdfeaea71ec5360d7c9d1b9deac'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1504/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='51feabdfeaea71ec5360d7c9d1b9deac'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945467"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='51feabdfeaea71ec5360d7c9d1b9deac'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945467"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13430" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="Codeforces Round #712 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13445" resourceName="Codeforces Round #712 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1504">Задачи</a></li> <li><a href="/contest/1504/submit">Отослать</a></li> <li><a href="/contest/1504/my">Мои посылки</a></li> <li><a href="/contest/1504/status">Статус</a></li> <li><a href="/contest/1504/hacks">Взломы</a></li> <li><a href="/contest/1504/room/1">Комната</a></li> <li><a href="/contest/1504/standings">Положение</a></li> <li><a href="/contest/1504/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d0ec3ec23c0b3841ebc8753735dd45d6866203ec"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Задача коммивояжёра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть $$$n$$$ городов, пронумерованных от $$$1$$$ до $$$n$$$, красота города $$$i$$$ равна $$$a_i$$$.</p><p>Коммивояжёр хочет начать с города $$$1$$$, посетить каждый город ровно один раз и вернуться в город $$$1$$$.</p><p>Для всех $$$i\ne j$$$, перелет из города $$$i$$$ в город $$$j$$$ стоит $$$\max(c_i,a_j-a_i)$$$ долларов, где $$$c_i$$$ — это нижний порог цены, наложенный на перелет городом $$$i$$$. Обратите внимание, что здесь не берется абсолютное значение. Найдите минимальную общую стоимость поездки для коммивояжёра.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое $$$n$$$ ($$$2\le n\le 10^5$$$) — количество городов.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится по два целых числа $$$a_i$$$, $$$c_i$$$ ($$$0\le a_i,c_i\le 10^9$$$) — красота и нижний порог цены города $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальную суммарную стоимость.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 9 2 1 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 2 8 4 3 0 2 3 7 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере мы можем путешествовать в порядке $$$1\to 3\to 2\to 1$$$. </p><ul> <li> Рейс $$$1\to 3$$$ стоит $$$\max(c_1,a_3-a_1)=\max(9,4-1)=9$$$. </li><li> Рейс $$$3\to 2$$$ стоит $$$\max(c_3, a_2-a_3)=\max(1,2-4)=1$$$. </li><li> Рейс $$$2\to 1$$$ стоит $$$\max(c_2,a_1-a_2)=\max(1,1-2)=1$$$. </li></ul><p>Общая стоимость составляет $$$11$$$, и мы не можем обойтись меньшим числом долларов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:07</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bef4ef7e1687',t:'MTY5NjY2NzA0Ny4yNDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \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", "\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\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"]
1504F
1504
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$$$ карт. На карте $$$i$$$ на лицевой стороне написано число $$$a_i$$$, а на оборотной — $$$b_i$$$. Каждое целое число от $$$1$$$ до $$$2n$$$ встречается на картах ровно один раз.</p><p>Колода называется отсортированной, если лицевые значения находятся в порядке <span class="tex-font-style-bf">возрастания</span>, а оборотные — в порядке <span class="tex-font-style-bf">убывания</span>. То есть, если $$$a_i&lt; a_{i+1}$$$ и $$$b_i&gt; b_{i+1}$$$ для всех $$$1\le i&lt;n$$$.</p><p>Перевернуть карту $$$i$$$ означает поменять местами значения $$$a_i$$$ и $$$b_i$$$. Вы должны перевернуть некоторое подмножество карт (возможно, ни одной), а затем разместить эти карты в каком-то порядке. Какое минимальное количество карт вы должны перевернуть, чтобы отсортировать колоду?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — количество карт.</p><p>Следующие $$$n$$$ строк описывают карты. $$$i$$$-я из этих строк содержит два целых числа $$$a_i, b_i$$$ ($$$1\le a_i, b_i\le 2n$$$). Каждое целое число от $$$1$$$ до $$$2n$$$ встречается ровно один раз.</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> 5 3 10 6 4 1 9 5 8 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 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> 3 1 2 3 6 4 5 </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, 9)$$$ и $$$(2, 7)$$$. Затем карты располагают в порядке $$$(3,10), (5,8), (6,4), (7,2), (9,1)$$$. Колода отсортирована потому, что $$$3&lt;5&lt;6&lt;7&lt;9$$$ и $$$10&gt;8&gt;4&gt;2&gt;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="f65d35dd196075c97dc4b255204fa2d6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="23fb4b555d0b12580ceb2f448033070f43802043"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f65d35dd196075c97dc4b255204fa2d6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1504%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='f65d35dd196075c97dc4b255204fa2d6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1504">Codeforces Round 712 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='f65d35dd196075c97dc4b255204fa2d6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1504/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="2-SAT (2-satisfiability)"> 2-sat </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='f65d35dd196075c97dc4b255204fa2d6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="945468"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f65d35dd196075c97dc4b255204fa2d6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="945468"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89227" title="Codeforces Round #712" target="_blank">Codeforces Round #712 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13430" resourceName="Codeforces Round #712" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89319" title="Codeforces Round #712 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13445" resourceName="Codeforces Round #712 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1504">Задачи</a></li> <li><a href="/contest/1504/submit">Отослать</a></li> <li><a href="/contest/1504/my">Мои посылки</a></li> <li><a href="/contest/1504/status">Статус</a></li> <li><a href="/contest/1504/hacks">Взломы</a></li> <li><a href="/contest/1504/room/1">Комната</a></li> <li><a href="/contest/1504/standings">Положение</a></li> <li><a href="/contest/1504/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cb87354e638fefadbeac221fbe16dfc5ee67cefd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$ карт. На карте $$$i$$$ на лицевой стороне написано число $$$a_i$$$, а на оборотной — $$$b_i$$$. Каждое целое число от $$$1$$$ до $$$2n$$$ встречается на картах ровно один раз.</p><p>Колода называется отсортированной, если лицевые значения находятся в порядке <span class="tex-font-style-bf">возрастания</span>, а оборотные — в порядке <span class="tex-font-style-bf">убывания</span>. То есть, если $$$a_i&lt; a_{i+1}$$$ и $$$b_i&gt; b_{i+1}$$$ для всех $$$1\le i&lt;n$$$.</p><p>Перевернуть карту $$$i$$$ означает поменять местами значения $$$a_i$$$ и $$$b_i$$$. Вы должны перевернуть некоторое подмножество карт (возможно, ни одной), а затем разместить эти карты в каком-то порядке. Какое минимальное количество карт вы должны перевернуть, чтобы отсортировать колоду?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — количество карт.</p><p>Следующие $$$n$$$ строк описывают карты. $$$i$$$-я из этих строк содержит два целых числа $$$a_i, b_i$$$ ($$$1\le a_i, b_i\le 2n$$$). Каждое целое число от $$$1$$$ до $$$2n$$$ встречается ровно один раз.</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> 5 3 10 6 4 1 9 5 8 2 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 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> 3 1 2 3 6 4 5 </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, 9)$$$ и $$$(2, 7)$$$. Затем карты располагают в порядке $$$(3,10), (5,8), (6,4), (7,2), (9,1)$$$. Колода отсортирована потому, что $$$3&lt;5&lt;6&lt;7&lt;9$$$ и $$$10&gt;8&gt;4&gt;2&gt;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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:08</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124befcefbc7b1b',t:'MTY5NjY2NzA0OC41NDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["2-SAT (2-satisfiability)", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\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"]
["2-sat", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"]
1505A
1505
A
ru
A. Is it rated - 2
<div class="problem-statement"><div class="header"><div class="title">A. Is it rated - 2</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><div><div class="section-title">Протокол взаимодействия</div><p>Эта задача - интерактивная. Вы можете прочитать задаваемые вопросы из стандартного потока ввода, и выводить свои ответы в стандартный поток вывода. Количество вопросов неизвестно заранее, так что вам придется обрабатывать их по мере их поступления, пока вы не достигнете конца файла.</p><p>В каждом запросе вам зададут один вопрос, записанный в одной строке. Вы должны ответить на него правильно, терпеливо и без эмоций. Ваш ответ обрабатывается без учета регистра.</p><p>Пожалуйста, используйте оператор flush после каждого запроса, чтобы не оставить часть запроса в буфере.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> Is it rated? Is it rated? Is it rated? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO NO NO</pre></div></div></div></div><p> </p></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f2b8ec5e1fb6c41bc2b77207cc71e703"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f2b8ec5e1fb6c41bc2b77207cc71e703'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='f2b8ec5e1fb6c41bc2b77207cc71e703'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='f2b8ec5e1fb6c41bc2b77207cc71e703'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='f2b8ec5e1fb6c41bc2b77207cc71e703'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943623"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f2b8ec5e1fb6c41bc2b77207cc71e703'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943623"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cd50c1209503142d10280b796d0ce1caa74aedc1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Is it rated - 2</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><div><div class="section-title">Протокол взаимодействия</div><p>Эта задача - интерактивная. Вы можете прочитать задаваемые вопросы из стандартного потока ввода, и выводить свои ответы в стандартный поток вывода. Количество вопросов неизвестно заранее, так что вам придется обрабатывать их по мере их поступления, пока вы не достигнете конца файла.</p><p>В каждом запросе вам зададут один вопрос, записанный в одной строке. Вы должны ответить на него правильно, терпеливо и без эмоций. Ваш ответ обрабатывается без учета регистра.</p><p>Пожалуйста, используйте оператор flush после каждого запроса, чтобы не оставить часть запроса в буфере.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> Is it rated? Is it rated? Is it rated? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO NO NO</pre></div></div></div></div><p> </p></div></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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:09</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf050a0a9d99',t:'MTY5NjY2NzA0OS45NzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0438 \u0434\u0440.", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*900"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505B
1505
B
ru
B. DMCA
<div class="problem-statement"><div class="header"><div class="title">B. DMCA</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>Многие знают о DMCA – Digital Millennium Copyright Act (Закон об авторском праве в цифровую эпоху). Но мало кто знает о другом недавно предложенном DMCA – Digital Millennium Calculation Act (Закон о вычислениях в цифровую эпоху).</p><p>В этой задаче вам нужно найти корень числа в соответствии с этим новым законом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат одно целое число $$$a$$$ ($$$1 \le a \le 1000000$$$).</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 81 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 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="7037b103e673b2bfd497f6ea618484f6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7037b103e673b2bfd497f6ea618484f6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='7037b103e673b2bfd497f6ea618484f6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='7037b103e673b2bfd497f6ea618484f6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='7037b103e673b2bfd497f6ea618484f6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943624"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7037b103e673b2bfd497f6ea618484f6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943624"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_92dbfbae6bd6908b18fb959d98356548a6034a1c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. DMCA</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>Многие знают о DMCA – Digital Millennium Copyright Act (Закон об авторском праве в цифровую эпоху). Но мало кто знает о другом недавно предложенном DMCA – Digital Millennium Calculation Act (Закон о вычислениях в цифровую эпоху).</p><p>В этой задаче вам нужно найти корень числа в соответствии с этим новым законом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат одно целое число $$$a$$$ ($$$1 \le a \le 1000000$$$).</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 81 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:11</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf0e1bab4979',t:'MTY5NjY2NzA1MS4zMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505C
1505
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><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из одной строки символов английского алфавита в верхнем регистре A-Z. Длина строки - от 1 до 10 символов, включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «YES» или «NO».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> HELP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> AID </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> MARY </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> ANNA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> MUG </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> CUP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> SUM </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> PRODUCT </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div></div><p> </p></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="6fd889d6936e70fbfa1f2c08d50ae11c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6fd889d6936e70fbfa1f2c08d50ae11c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='6fd889d6936e70fbfa1f2c08d50ae11c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6fd889d6936e70fbfa1f2c08d50ae11c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='6fd889d6936e70fbfa1f2c08d50ae11c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943625"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6fd889d6936e70fbfa1f2c08d50ae11c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943625"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7265ddc5a3c87ab9faed0e08200c029cda128967"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из одной строки символов английского алфавита в верхнем регистре A-Z. Длина строки - от 1 до 10 символов, включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «YES» или «NO».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> HELP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> AID </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> MARY </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> ANNA </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> MUG </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> CUP </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> SUM </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> PRODUCT </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div></div><p> </p></div></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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:12</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf165fc57b73',t:'MTY5NjY2NzA1Mi42OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1400"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505D
1505
D
ru
D. Xenolith? Hippodrome?
<div class="problem-statement"><div class="header"><div class="title">D. Xenolith? Hippodrome?</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><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат два целых числа $$$N$$$, $$$M$$$ ($$$1 \le N \le 1024, 2 \le M \le 16$$$), разделенных пробелом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «YES» или «NO».</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 33 16 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 26 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div></div><p> </p></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="0e1438ca1a6ce2faea8f4a8ca20507c0"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0e1438ca1a6ce2faea8f4a8ca20507c0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='0e1438ca1a6ce2faea8f4a8ca20507c0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='0e1438ca1a6ce2faea8f4a8ca20507c0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='0e1438ca1a6ce2faea8f4a8ca20507c0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943626"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0e1438ca1a6ce2faea8f4a8ca20507c0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943626"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d4360d69bfa04018c961894140e31a3864bb0f46"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Xenolith? Hippodrome?</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><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат два целых числа $$$N$$$, $$$M$$$ ($$$1 \le N \le 1024, 2 \le M \le 16$$$), разделенных пробелом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «YES» или «NO».</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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 33 16 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 26 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div></div><p> </p></div></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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:14</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf1f0bd69daa',t:'MTY5NjY2NzA1NC4wNjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1800"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505E
1505
E
ru
E. Прогулка по торту
<div class="problem-statement"><div class="header"><div class="title">E. Прогулка по торту</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Мышь нашла большой красивый торт и решила прогуляться по нему, попутно объедая ягоды на верхушке торта. Торт прямоугольный и разделен на аккуратные квадраты; в некоторых квадратах есть ягода, а в некоторых нет.</p><p>Мышь спешит, поэтому когда она взберется на торт в его северо-западном углу (вернняя левая клетка входных данных), она будет двигаться только на восток (направо) или на юг (вниз), пока не достигнет юго-восточного угла (нижняя правая клетка). Она съест все ягоды на клетках, через которые она пройдет, и оставит остальные ягоды нетронутыми.</p><p>Мышь хочет выбрать свой путь так, чтобы съесть наибольшее возможное количество ягод. Но, возможно, ее спешка и голод затмевают ее разум и вынуждают ее принимать неоптимальные решения...</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных состоит из двух чисел $$$H$$$ и $$$W$$$ ($$$1 \le H, W \le 5$$$), разделенных пробелом - высоты и ширины торта.</p><p>Следующие $$$H$$$ строк содержат строки из ровно $$$W$$$ символов, описывающих квадраты торта: «.» представляет пустой квадрат, а «*» - квадрат с ягодой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число - количество ягод, которые съест мышь, следуя своей стратегии.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 *.. .*. ..* ... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 .*.. *... ...* ..*. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 ..** *... .... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 ..*.. ..... **... **... **... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 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="55b77daff69b9bb6211813e08b6ec3ab"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='55b77daff69b9bb6211813e08b6ec3ab'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='55b77daff69b9bb6211813e08b6ec3ab'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='55b77daff69b9bb6211813e08b6ec3ab'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='55b77daff69b9bb6211813e08b6ec3ab'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943627"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='55b77daff69b9bb6211813e08b6ec3ab'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943627"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_51e8c84a62f40dedfbb160996e404fbc2561cd4c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Прогулка по торту</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Мышь нашла большой красивый торт и решила прогуляться по нему, попутно объедая ягоды на верхушке торта. Торт прямоугольный и разделен на аккуратные квадраты; в некоторых квадратах есть ягода, а в некоторых нет.</p><p>Мышь спешит, поэтому когда она взберется на торт в его северо-западном углу (вернняя левая клетка входных данных), она будет двигаться только на восток (направо) или на юг (вниз), пока не достигнет юго-восточного угла (нижняя правая клетка). Она съест все ягоды на клетках, через которые она пройдет, и оставит остальные ягоды нетронутыми.</p><p>Мышь хочет выбрать свой путь так, чтобы съесть наибольшее возможное количество ягод. Но, возможно, ее спешка и голод затмевают ее разум и вынуждают ее принимать неоптимальные решения...</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных состоит из двух чисел $$$H$$$ и $$$W$$$ ($$$1 \le H, W \le 5$$$), разделенных пробелом - высоты и ширины торта.</p><p>Следующие $$$H$$$ строк содержат строки из ровно $$$W$$$ символов, описывающих квадраты торта: «.» представляет пустой квадрат, а «*» - квадрат с ягодой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число - количество ягод, которые съест мышь, следуя своей стратегии.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 *.. .*. ..* ... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 .*.. *... ...* ..*. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 ..** *... .... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 5 ..*.. ..... **... **... **... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:15</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf279a2116c7',t:'MTY5NjY2NzA1NS40MjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0438 \u0434\u0440.", "\u0416\u0430\u0434\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", "\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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1800"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505F
1505
F
ru
F. Математика
<div class="problem-statement"><div class="header"><div class="title">F. Математика</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6c5613adc71f63dd8f58754dd1351e0a4a8309e1.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/863a3d380b9f4328d252c3b4e781205b1811bf3d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>*Эти два изображения эквивалентны, вы можете использовать любое из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат одно целое число $$$a$$$ ($$$-100 \le a \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ – целое число.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 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="ad44af30710079d71b7f71d8df67feb3"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ad44af30710079d71b7f71d8df67feb3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='ad44af30710079d71b7f71d8df67feb3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='ad44af30710079d71b7f71d8df67feb3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='ad44af30710079d71b7f71d8df67feb3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943628"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ad44af30710079d71b7f71d8df67feb3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943628"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8eb740914abecc2d3452abddd0f98a88225cffca"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Математика</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6c5613adc71f63dd8f58754dd1351e0a4a8309e1.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/863a3d380b9f4328d252c3b4e781205b1811bf3d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>*Эти два изображения эквивалентны, вы можете использовать любое из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные содержат одно целое число $$$a$$$ ($$$-100 \le a \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ – целое число.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:16</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf301e439d84',t:'MTY5NjY2NzA1Ni44NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0438 \u0434\u0440.", "\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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2200"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505G
1505
G
ru
G. Закодированное сообщение
<div class="problem-statement"><div class="header"><div class="title">G. Закодированное сообщение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит единственное целое число $$$N$$$ ($$$1 \le N \le 24$$$). Следующие $$$N$$$ строк содержат по $$$5$$$ целых чисел, разделенных пробелами. Первые три числа находятся в диапазоне от 0 до 2, включительно, последние два – от 0 до 3, включительно. Сумма первых трех чисел равна сумме двух последних.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите результат – строку латинских букв в нижнем регистре.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 1 0 0 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> a </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 2 0 0 1 1 1 1 1 2 1 2 1 0 1 2 1 1 0 1 1 2 1 0 2 1 1 1 1 2 1 1 2 1 3 1 2 0 0 1 1 1 1 0 1 1 1 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> codeforcez </pre></div></div></div></div><p> </p></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3b85501a68b99c1a641c532d698b032a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='3b85501a68b99c1a641c532d698b032a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='3b85501a68b99c1a641c532d698b032a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='3b85501a68b99c1a641c532d698b032a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='3b85501a68b99c1a641c532d698b032a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943629"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3b85501a68b99c1a641c532d698b032a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943629"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9ea597257a059ff1e0157156b0197e9ac902db65"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Закодированное сообщение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит единственное целое число $$$N$$$ ($$$1 \le N \le 24$$$). Следующие $$$N$$$ строк содержат по $$$5$$$ целых чисел, разделенных пробелами. Первые три числа находятся в диапазоне от 0 до 2, включительно, последние два – от 0 до 3, включительно. Сумма первых трех чисел равна сумме двух последних.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите результат – строку латинских букв в нижнем регистре.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 1 0 0 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> a </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 2 0 0 1 1 1 1 1 2 1 2 1 0 1 2 1 1 0 1 1 2 1 0 2 1 1 1 1 2 1 1 2 1 3 1 2 0 0 1 1 1 1 0 1 1 1 1 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> codeforcez </pre></div></div></div></div><p> </p></div></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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:18</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf390b241625',t:'MTY5NjY2NzA1OC4xOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \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"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2600"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1505H
1505
H
ru
H. L BREAK into program
<div class="problem-statement"><div class="header"><div class="title">H. L BREAK into program</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 href="http://tc-alchemy.progopedia.com/l.z80">программу</a> и получите пароль, зашифрованный в ней.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В этой задаче ровно один тест, и он пустой (вашей программе ничего не подается на вход).</p></div><div class="output-specification"><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="6aff03ad9aa4eebf7886459651395848"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="3382ab67cefb526a84f484603acb2d319d0bc032"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6aff03ad9aa4eebf7886459651395848'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1505%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='6aff03ad9aa4eebf7886459651395848'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1505">April Fools Day Contest 2021</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Языки <div class="top-links"> </div> </div> <div style="margin:1em;"> <div style="font-size:0.8em;">Следующие языки могут быть использованы как дополнительные для решения задач соревнования</div><div style="font-weight:bold;margin:0.5em 0;font-size:0.8em;text-align:center;">April Fools Day Contest 2021:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Secret 2021</li> </ul> </div> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6aff03ad9aa4eebf7886459651395848'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1505/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Особые требования к решению задачи, например, использование неизвестного языка программирования и др."> *особая задача </span> </div> <div class="roundbox borderTopRound 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='6aff03ad9aa4eebf7886459651395848'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="943630"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6aff03ad9aa4eebf7886459651395848'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="943630"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88840" title="Первоапрельский контест 2021" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13365:13366" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89260" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13427" resourceName="tutorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1505">Задачи</a></li> <li><a href="/contest/1505/submit">Отослать</a></li> <li><a href="/contest/1505/my">Мои посылки</a></li> <li><a href="/contest/1505/status">Статус</a></li> <li><a href="/contest/1505/standings">Положение</a></li> <li><a href="/contest/1505/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1a6ec92c7002b84f177f697eb4cad58d934ac968"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">H. L BREAK into program</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 href="http://tc-alchemy.progopedia.com/l.z80">программу</a> и получите пароль, зашифрованный в ней.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В этой задаче ровно один тест, и он пустой (вашей программе ничего не подается на вход).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите пароль, добытый из программы. Пароль чувствителен к регистру.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:19</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf415bec3a55',t:'MTY5NjY2NzA1OS41NjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041e\u0441\u043e\u0431\u044b\u0435 \u0442\u0440\u0435\u0431\u043e\u0432\u0430\u043d\u0438\u044f \u043a \u0440\u0435\u0448\u0435\u043d\u0438\u044e \u0437\u0430\u0434\u0430\u0447\u0438, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u043d\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e\u0433\u043e \u044f\u0437\u044b\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["*\u043e\u0441\u043e\u0431\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "*2500"]
https://codeforces.com/blog/entry/89260
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b752a7fb9d318e498b38e7212f543295"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "en"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="h1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/81027/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="April Fools Day Contest 2021: editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>April Fools Day Contest 2021: editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b752a7fb9d318e498b38e7212f543295'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "en"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/81027/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/81027/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/81027/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fblog%2Fentry%2F89260">Enter</a> | <a href="/register">Register</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Home</a></li> <li class=""><a href="/top">Top</a></li> <li class=""><a href="/catalog">Catalog</a></li> <li class=""><a href="/contests">Contests</a></li> <li class=""><a href="/gyms">Gym</a></li> <li class=""><a href="/problemset">Problemset</a></li> <li class=""><a href="/groups">Groups</a></li> <li class=""><a href="/ratings">Rating</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Calendar</a></li> <li class=""><a href="/help">Help</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Pay attention <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div style="text-align:center;border-bottom: 1px solid rgb(185, 185, 185);margin:0 -0.5em 0.5em -0.5em;padding: 0 1em 0.5em 1em;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 1, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1876">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> <div style="text-align:center;"> <span class='contest-state-phase'>Before contest</span><br/><a href="/contests/1876,1877">Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round)</a><br/><span class='countdown' home='//codeforces.org/s/81027' noRedirection='true' textBeforeRedirect=''>13:32:26</span><br/><a href="/contestRegistration/1877">Register now »</a><div class="smaller notice">*has extra registration<i class="icon-question-sign clickable-title" title="If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes."></i></div> </div> </div> </div> <style data-nocturne="true" type="text/css"> ._StreamsSidebarFrame_frame { padding: 0.5em 0.5em 0 0.5em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream { text-align: center; border-bottom: 1px solid #b9b9b9; margin: 0 -0.5em 0.5em -0.5em; padding: 0 1em 0.5em 1em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_user { margin: 0 0 0.5em 0; font-size: 0.8em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream ._StreamsSidebarFrame_timeMark { color: #777; font-size: 0.9em; } ._StreamsSidebarFrame_frame ._StreamsSidebarFrame_stream:last-of-type { border-bottom: unset; margin: unset; padding: 0 0.5em 0.5em 1em; } ._StreamsSidebarFrame_frame ._viewAll { text-align: right; } .moreRunningStreamsSidebarNote { color: #777 !important; text-decoration: none; } </style> <script data-nocturne="true"> $(function () { }); </script> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top rated <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Rating</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/tourist" title="Legendary Grandmaster tourist" class="rated-user user-legendary"><span class="legendary-user-first-letter">t</span>ourist</a></td> <td class=" dark">3775</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/Benq" title="Legendary Grandmaster Benq" class="rated-user user-legendary"><span class="legendary-user-first-letter">B</span>enq</a></td> <td class="">3724</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/orzdevinwang" title="Legendary Grandmaster orzdevinwang" class="rated-user user-legendary"><span class="legendary-user-first-letter">o</span>rzdevinwang</a></td> <td class=" dark">3697</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Radewoosh" title="Legendary Grandmaster Radewoosh" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>adewoosh</a></td> <td class="">3651</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/jiangly" title="Legendary Grandmaster jiangly" class="rated-user user-legendary"><span class="legendary-user-first-letter">j</span>iangly</a></td> <td class=" dark">3632</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/cnnfls_csy" title="Legendary Grandmaster cnnfls_csy" class="rated-user user-legendary"><span class="legendary-user-first-letter">c</span>nnfls_csy</a></td> <td class="">3620</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/-0.5" title="Legendary Grandmaster -0.5" class="rated-user user-legendary"><span class="legendary-user-first-letter">-</span>0.5</a></td> <td class=" dark">3545</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/inaFSTream" title="Legendary Grandmaster inaFSTream" class="rated-user user-legendary"><span class="legendary-user-first-letter">i</span>naFSTream</a></td> <td class="">3478</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/fantasy" title="Legendary Grandmaster fantasy" class="rated-user user-legendary"><span class="legendary-user-first-letter">f</span>antasy</a></td> <td class=" dark">3468</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/Rebelz" title="Legendary Grandmaster Rebelz" class="rated-user user-legendary"><span class="legendary-user-first-letter">R</span>ebelz</a></td> <td class="bottom">3415</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> <a href="/ratings/countries">Countries</a> | <a href="/ratings/cities">Cities</a> | <a href="/ratings/organizations">Organizations</a> </td> <td style="text-align:right;"> <a href="/ratings">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <div class="roundbox sidebox top-contributed borderTopRound " style=""> <div class="caption titled">&rarr; Top contributors <div class="top-links"> </div> </div> <table class="rtable "> <tbody> <tr> <th class="left" style="width:2.25em;">#</th> <th class="">User</th> <th class="" style="width:5em;">Contrib.</th> </tr> <tr> <td class="left dark">1</td> <td class=" dark"><a href="/profile/adamant" title="Grandmaster adamant" class="rated-user user-red">adamant</a></td> <td class=" dark">178</td> </tr> <tr> <td class="left ">2</td> <td class=""><a href="/profile/awoo" title="Master awoo" class="rated-user user-orange">awoo</a></td> <td class="">167</td> </tr> <tr> <td class="left dark">3</td> <td class=" dark"><a href="/profile/BledDest" title="International Grandmaster BledDest" class="rated-user user-red">BledDest</a></td> <td class=" dark">165</td> </tr> <tr> <td class="left ">4</td> <td class=""><a href="/profile/Um_nik" title="Legendary Grandmaster Um_nik" class="rated-user user-legendary"><span class="legendary-user-first-letter">U</span>m_nik</a></td> <td class="">163</td> </tr> <tr> <td class="left dark">5</td> <td class=" dark"><a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a></td> <td class=" dark">162</td> </tr> <tr> <td class="left ">6</td> <td class=""><a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a></td> <td class="">160</td> </tr> <tr> <td class="left dark">7</td> <td class=" dark"><a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a></td> <td class=" dark">158</td> </tr> <tr> <td class="left ">8</td> <td class=""><a href="/profile/-is-this-fft-" title="Grandmaster -is-this-fft-" class="rated-user user-red">-is-this-fft-</a></td> <td class="">152</td> </tr> <tr> <td class="left dark">9</td> <td class=" dark"><a href="/profile/kostka" title="International Grandmaster kostka" class="rated-user user-red">kostka</a></td> <td class=" dark">145</td> </tr> <tr> <td class="left bottom">10</td> <td class="bottom"><a href="/profile/TheScrasse" title="International Grandmaster TheScrasse" class="rated-user user-red">TheScrasse</a></td> <td class="bottom">144</td> </tr> </tbody> </table> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/top-contributed">View all &rarr;</a> </td> </tr> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Find user <div class="top-links"> </div> </div> <form class="handleForm" method="post"><input type='hidden' name='csrf_token' value='b752a7fb9d318e498b38e7212f543295'/> <div style="padding:1em;text-align:right;"> <label style="padding-right:1em;">Handle: <input style="width:12em;" type="text" class="handleBox"/> </label> </div> <div style="padding: 0 1em 1em 1em;text-align:right;"> <input style="height:1.65em;padding:0 0.75em;" type="submit" value="Find"/> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $(".handleBox").autocomplete("/data/handles", { delay: 200, width: 200, selectFirst: false, matchContains: true, minChars: 3 }); $(".handleForm").attr("autocomplete", "off").submit(function () { var link = "/profile/userHandle".replace( "userHandle", $(this).find(".handleBox").val() ); window.location = link; return false; }); }); </script> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Recent actions <div class="top-links"> </div> </div> <div class="recent-actions"> <ul> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/121073">Meta Hacker Cup 2023 Round 1</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/nor" title="Master nor" class="rated-user user-orange">nor</a> &rarr; <a href="/blog/entry/120772">PSA: Increase your stack size before the Meta Hacker Cup, here&#39;s how</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/.Danet" title="Expert .Danet" class="rated-user user-blue">.Danet</a> &rarr; <a href="/blog/entry/121172">[TLE on pretest1]</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pyqe" title="International Grandmaster Pyqe" class="rated-user user-red">Pyqe</a> &rarr; <a href="/blog/entry/121025">Codeforces Round #902 (Div. 1, Div. 2, based on COMPFEST 15 — Final Round)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Pranshu_Pandya" title="Specialist Pranshu_Pandya" class="rated-user user-cyan">Pranshu_Pandya</a> &rarr; <a href="/blog/entry/121171">An Interesting Tree Problem</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/sszcdjr" title="Master sszcdjr" class="rated-user user-orange">sszcdjr</a> &rarr; <a href="/blog/entry/119859">Codeforces Round 896 (Div. 1, Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/SecondThread" title="Master SecondThread" class="rated-user user-orange">SecondThread</a> &rarr; <a href="/blog/entry/119880">It&#39;s Happening! Meta Hacker Cup 2023 Schedule</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/DaviddeGea1" title="Expert DaviddeGea1" class="rated-user user-blue">DaviddeGea1</a> &rarr; <a href="/blog/entry/70917">Number of ways of dividing an array into 2 parts such that sum of each part is &gt; k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bekh" title="Master Bekh" class="rated-user user-orange">Bekh</a> &rarr; <a href="/blog/entry/74245">Questions and doubts regarding Aliens DP trick</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/cgy4ever" title="International Grandmaster cgy4ever" class="rated-user user-red">cgy4ever</a> &rarr; <a href="/blog/entry/8192">Codeforces Round #190 — Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/hocky" title="Candidate Master hocky" class="rated-user user-violet">hocky</a> &rarr; <a href="/blog/entry/95323">FBHC wuining uw Day? Incwease uw stacc size! (ㅅ´ ˘ `)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/liouzhou_101" title="International Master liouzhou_101" class="rated-user user-orange">liouzhou_101</a> &rarr; <a href="/blog/entry/87598">Editorial of Codeforces Round #700</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/yeon_gist" title="Newbie yeon_gist" class="rated-user user-gray">yeon_gist</a> &rarr; <a href="/blog/entry/121170">plusMinusPermutation computing error</a> &nbsp;&nbsp;<img alt="Text created or updated" title="Text created or updated" src="//codeforces.org/s/81027/images/icons/x-update-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/altforminuscontribution" title="Newbie altforminuscontribution" class="rated-user user-gray">altforminuscontribution</a> &rarr; <a href="/blog/entry/121162">My screen get unexpectedly big, what should I do</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/atcoder_official" title="Unrated, atcoder_official" class="rated-user user-black">atcoder_official</a> &rarr; <a href="/blog/entry/121120">We will hold UNIQUE VISION Programming Contest 2023 Autumn(AtCoder Beginner Contest 323)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/YouStill_DontKnowMeYet" title="Candidate Master YouStill_DontKnowMeYet" class="rated-user user-violet">YouStill_DontKnowMeYet</a> &rarr; <a href="/blog/entry/117659">[GYM] Al-Baath Collegiate Programming Contest 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/ankancool" title="Expert ankancool" class="rated-user user-blue">ankancool</a> &rarr; <a href="/blog/entry/121136">Invitation to AstroByte 2023</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/GeZhiyuan" title="Grandmaster GeZhiyuan" class="rated-user user-red">GeZhiyuan</a> &rarr; <a href="/blog/entry/120943">Codeforces Round 901 (Div. 1, Div. 2) Editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/dino_merlin" title="Expert dino_merlin" class="rated-user user-blue">dino_merlin</a> &rarr; <a href="/blog/entry/121145">Intuitive approach for CEOI Kangaroo?</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/icecuber" title="Grandmaster icecuber" class="rated-user user-red">icecuber</a> &rarr; <a href="/blog/entry/70018">CSES DP section editorial</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Bn00b" title="Newbie Bn00b" class="rated-user user-gray">Bn00b</a> &rarr; <a href="/blog/entry/98820">[FEATURE REQUEST : ATCODER] TOPICS TAGS AND SORTING BY SOLVE COUNT</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> <img alt="Necropost" title="Necropost" src="//codeforces.org/s/81027/images/icons/hourglass.png" style="vertical-align:middle; position: relative; top: 1px;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/maroonrk" title="Legendary Grandmaster maroonrk" class="rated-user user-legendary"><span class="legendary-user-first-letter">m</span>aroonrk</a> &rarr; <a href="/blog/entry/121163">AtCoder Regular Contest 166 Announcement</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/windva" title="Grandmaster windva" class="rated-user user-red">windva</a> &rarr; <a href="/blog/entry/120644">Codeforces Round 899 (Div. 2)</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/Misa-Misa" title="Expert Misa-Misa" class="rated-user user-blue">Misa-Misa</a> &rarr; <a href="/blog/entry/121157">Someone please help me understand this.</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> <li><div style="font-size:0.9em;padding:0.5em 0;"> <a href="/profile/shivam565" title="Specialist shivam565" class="rated-user user-cyan">shivam565</a> &rarr; <a href="/blog/entry/108348">Total number of subarrays with sum atmost k</a> &nbsp;&nbsp;<img alt="New comment(s)" title="New comment(s)" src="//codeforces.org/s/81027/images/icons/comment-12x12.png" style="vertical-align:middle;"/> </div> </li> </ul> </div> <div class="bottom-links"> <table style="width:100%;"> <tbody> <tr> <td style="text-align:left;"> </td> <td style="text-align:right;"> <a href="/recent-actions">Detailed &rarr;</a> </td> </tr> </tbody> </table> </div> </div> </div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li><a href="/profile/Nickolas">Nickolas</a></li> <li class="current selectedLava"><a href="/blog/Nickolas">Blog</a></li> <li><a href="/teams/with/Nickolas">Teams</a></li> <li><a href="/submissions/Nickolas">Submissions</a></li> <li><a href="/groups/with/Nickolas">Groups</a></li> <li><a href="/contests/with/Nickolas">Contests</a></li> <li><a href="/contests/writer/Nickolas">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/Nickolas" style="text-decoration:none;color:black !important;">Nickolas's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="89866"> <div class="title"> <a href="/blog/entry/89260"> <p>April Fools Day Contest 2021: editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a>, <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span>, <img style="position: relative;top: 5px;" src="//codeforces.org/s/81027/images/flags/24/gb.png" alt="In English" title="In English"/> <span style="position:absolute;right:0;top:0.05em;margin-right:1em;display:inline;font-size:0.75em;"> <div style="margin-top:0.25em;"> </div> </span> </div> <div class="content"> <div class="ttypography"><h2><a href="/contest/1505/problem/A" title="April Fools Day Contest 2021">1505A - Is it rated - 2</a></h2><p>This problem described the task in quite a lot of detail. The main challenge was that it was interactive, so some effort was required to figure out the right sequence of reading from standard input, writing the answer and checking for end of file. Here is the code in Python:</p> <pre><code>while True: try: q = input() except EOFError: break print(&quot;no&quot;, flush=True) </code></pre><h2><a href="/contest/1505/problem/B" title="April Fools Day Contest 2021">1505B - DMCA</a></h2><p>As the problem statement strongly hinted, in this problem you had to calculate the <strong>digital</strong> root of the given number.</p><p>The digital root of a given number is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.</p><h2><a href="/contest/1505/problem/C" title="April Fools Day Contest 2021">1505C - Fibonacci Words</a></h2><p>YES or NO answer implies that you need to figure out whether the given word is a Fibonacci word. Similarly to the Fibonacci-style integer sequences, a Fibonacci word is a word for which each letter equals the sum of two previous ones. Unlike the integer sequences, for this definition to make sense we have to convert each letter to a number between 0 and 25, and perform addition modulo 26.</p><h2><a href="/contest/1505/problem/D" title="April Fools Day Contest 2021">1505D - Xenolith? Hippodrome?</a></h2><p>Again, YES or NO answer implies that you need to figure out whether the given pair of numbers describes something called something like &quot;hippodrome&quot;... Or was it &quot;xenolith&quot; after all? Neither of these options makes a lot of sense, but you know how it is when you're trying to remember a fancy-sounding word and come up with all kinds of similar-looking ones? The word you're looking for here is &quot;xenodrome&quot; — a number which, when written in a certain base, has no duplicate digits. This explains a lot: the given numbers $$$N$$$ and $$$M$$$ are the candidate number and the base, respectively; the task is to write $$$N$$$ in base $$$M$$$ and check whether all digits are unique.</p><h2><a href="/contest/1505/problem/E" title="April Fools Day Contest 2021">1505E - Cakewalk</a></h2><p>As the flavor text hinted and examples 3 and 4 confirmed, the mouse doesn't use an optimal strategy, but rather follows a greedy algorithm: it always goes for the nearest berry square, where the distance between squares is defined by Manhattan distance (i.e., the number of steps to the right or down that the mouse needs to take to get between them). In case of a tie, it goes for the square in the top row.</p><h2><a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a></h2><p>The images given encode a formula $$$2-x^2$$$ using Braille for math; the top image (the shorter one) gives Nemeth representation, and the bottom one — Universal English Braille. </p><h2><a href="/contest/1505/problem/G" title="April Fools Day Contest 2021">1505G - Encoded message</a></h2><p>The biggest hint for this problem is that it follows <a href="/contest/1505/problem/F" title="April Fools Day Contest 2021">1505F - Math</a>. Once you spent some time staring at Braille symbols, recognizing the pattern of 5 numbers becomes easier: the first three numbers and the last two are the numbers of dots in the rows and columns of the Braille symbol for the encoded letter, respectively. Typing in those numbers in the solution required a fair amount of focus, but I did it at 2 am and got them right on the first try, so I figured out it's realistic :-)</p><h2><a href="/contest/1505/problem/H" title="April Fools Day Contest 2021">1505H - L BREAK into program</a></h2><p>The given program is a ZX Spectrum emulator memory snapshot.</p><p>Here are the possible steps to solve the problem:</p> <ol> <li><p>Load the file into a ZX Spectrum emulator (there are many versions, even online ones).</p></li> <li><p>Press BREAK (usually Shift+Space in the emulator).</p></li> <li><p>Press LIST (k) to see the BASIC source code.</p></li> <li><p>Notice that the actual program (&quot;Admin zone&quot;) starts on line 1000.</p></li> <li><p>Execute &quot;RUN 1000&quot; and get &quot;Integer out of range&quot; error.</p></li> <li><p>Find a bug in the line 1150 and fix it by changing &quot;-&quot; to &quot;+&quot;, then re-run.</p></li> </ol><p>Line 1140 has a hidden comment about the bug. To see the comment, the background needs to be changed to a color different from white, by executing &quot;PAPER 4&quot;, for example. It's also possible to see the comment by looking at the snapshot file in a text editor.</p><p>Instead of fixing the BASIC program, it's also should be not too hard to understand the logic and re-implement it in a more conventional programming language.</p><h2><a href="/contest/1505/problem/I" title="April Fools Day Contest 2021">1505I - Mysterious language again, seriously?</a></h2><p>Unlike the past years, this time any code you submit in ``Secret 2021'' language will run successfully — or at least produce no recognizable error. The key hint at the solution can be found in the title: turns out <a href="https://github.com/Mego/Seriously">Seriously is a programming language</a>!</p><p>The next part of the challenge is figuring out how to print a message in this language — since most characters are valid commands, there's a lot of documentation to go through! There are multiple ways to print the right message (a lot of them undocumented). The reference solution used commands '1'-'9' to put corresponding numbers on the stack, '+' and '*' to perform addition and multiplication on the stack elements to get the necessary ASCII codes on the stack, 'c' to convert the integer ASCII code into the corresponding character, and '◙' to print the character on top of the stack.</p></div> </div> <div style="font-size: 1.1rem;line-height: 1.1rem;padding-bottom: 0.5em;"> <img src="//codeforces.org/s/81027/images/icons/paperclip-16x16.png" style="vertical-align: middle;"/> <span style="padding: 0 0.35em;">Tutorial of <a href="/contest/1505" class="notice" style="text-decoration: none;">April Fools Day Contest 2021</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-5202-89866").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "5202", blogEntryId: "89260", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div style="font-size: 1.1rem;line-height: 11px;"> <img style="vertical-align: middle;" src="//codeforces.org/s/81027/images/blog/tags.png" title="Tags" alt="Tags"/> <span style="padding: 0 0.35em;"> <a href="/search?query=april+fools+day+contest" class="tag notice" style="text-decoration: none;">april fools day contest</a> </span> </div> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/voteup.png" alt="Vote: I like it" title="Vote: I like it" /></a> </li> <li style="line-height: 1.6em;"> <span title="Topic rating" style='font-size:larger;position:relative;bottom:1px;font-weight:bold;color:green'>+140</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-89866"><img style="vertical-align:middle;position:relative;top:-0.2em" src="//codeforces.org/s/81027/images/actions/votedown.png" alt="Vote: I do not like it" title="Vote: I do not like it" /></a> </li> </ul> </div> <span style="position: relative; line-height: 1.65em; top: 0.75rem; left: 0.8em;"> </span> <div class="right-meta"> <ul> <li> <a href="/profile/Nickolas"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/user_16x16.png" alt="Author" title="Author" /></a> <a href="/profile/Nickolas"> Nickolas </a> </li> <li> <img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/date_16x16.png" alt="Publication date" title="Publication date" /> <span class="format-humantime" title="Apr/01/2021 19:36">3 years ago</span> </li> <li> <a href="/blog/entry/89260#comments"><img style="vertical-align:middle;position:relative;top:-1px" src="//codeforces.org/s/81027/images/blog/comments_16x16.png" alt="Comments" title="Comments" /></a> <a href="/blog/entry/89260#comments"> 55 </a> </li> </ul> </div> <br style="clear:both;"/> </div> <style type="text/css"> .comments .title { float: left; } .comments .comments-actions-div { float: right; margin-top: 3rem; margin-right: 0.5em; } .comments .comments-actions-div .separator { margin: 0 1rem; } .comments label.show-archived { } .comments label.show-archived, .comments label.show-archived * { font-size: 1.4rem !important; color: black !important; /*position: relative !important;*/ /*bottom: 0.4rem !important;*/ } .comments label.show-archived input { height: 1.4rem !important; width: 1.4rem !important; position: relative; top: 0.25rem; } .new-root-comment { font-size: 1.4rem !important; } </style> <div class="comments" commentableId="97591"> <div style="display: flow-root"> <div class="title"> <img src="//codeforces.org/s/81027/images/icons/comments-48x48.png" alt="Comments" title="Comments" style="position:relative;top:0.6em;"/> <a name="comments">Comments (40)</a> </div> <div class="comments-actions-div"> <label class="show-archived"> <input type="checkbox" class="show-archived-checkbox" /> Show archived </label> <span class="separator">|</span> <a href="#" class="new-root-comment" >Write comment?</a> </div> </div> <div class="comment"> <table class="comment-table" commentId="776638" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Yaduvans_hi" style="position: relative;"> <img src='https://userpic.codeforces.org/2006231/avatar/2da5634d418e0bfa.jpg'/> </a> <div><a href="/profile/Yaduvans_hi" title="Newbie Yaduvans_hi" class="rated-user user-gray">Yaduvans_hi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776638" href="?#comment-776638" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776638" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2006231" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776638"> <div class="moveup"> <div class="ttypography"><p>Awesome just after contest, medicine for my pain ;)</p></div> </div> </div> <div class="reply info"> <a class="comment-776638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776638"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776640" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pritishn" style="position: relative;"> <img src='https://userpic.codeforces.org/1015975/avatar/f9cc7e2cd45d5799.jpg'/> </a> <div><a href="/profile/pritishn" title="Candidate Master pritishn" class="rated-user user-violet">pritishn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:40">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776640" href="?#comment-776640" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776640" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1015975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776640"> <div class="moveup"> <div class="ttypography"><p>Thanks for the fast editorial. I desperately needed to see the solutions of B and E.</p></div> </div> </div> <div class="reply info"> <a class="comment-776640 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776640 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776640"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776643" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PinkRabbitAFO" style="position: relative;"> <img src='https://userpic.codeforces.org/443999/avatar/95b8435197740656.jpg'/> </a> <div><a href="/profile/PinkRabbitAFO" title="International Grandmaster PinkRabbitAFO" class="rated-user user-red">PinkRabbitAFO</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776643" href="?#comment-776643" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776643" class="CommentVoteFrame" data-commentRating="54" data-commentUserId="443999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+54</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776643"> <div class="moveup"> <div class="ttypography"><p>So what the hell is &quot;xenodrome&quot;, googled it and found nothing</p></div> </div> </div> <div class="reply info"> <a class="comment-776643 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776643 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776643"> <li> <div class="comment"> <table class="comment-table" commentId="776663" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zscoder" style="position: relative;"> <img src='https://userpic.codeforces.org/106090/avatar/af14a21416e11cd5.jpg'/> </a> <div><a href="/profile/zscoder" title="International Grandmaster zscoder" class="rated-user user-red">zscoder</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776663" href="?#comment-776663" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776663" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="106090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776663"> <div class="moveup"> <div class="ttypography"><p>Google xenodrome number</p></div> </div> </div> <div class="reply info"> <a class="comment-776663 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776663 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776663"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776672" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:50">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776672" href="?#comment-776672" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776672" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776672"> <div class="moveup"> <div class="ttypography"><p><a href="http://oeis.org/search?q=xenodrome">http://oeis.org/search?q=xenodrome</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776672 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776672 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776672"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776674" commentParentId="776643"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776674" href="?#comment-776674" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776643" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776674" class="CommentVoteFrame" data-commentRating="67" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+67</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776674"> <div class="moveup"> <div class="ttypography"><p>The only results appearing related to &quot;Xenodrome&quot; are of Ben 10 XD</p></div> </div> </div> <div class="reply info"> <a class="comment-776674 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776674 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776674"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776651" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Golovanov399" style="position: relative;"> <img src='https://userpic.codeforces.org/10266/avatar/946a27a591b9aa8.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Golovanov399" title="International Grandmaster Golovanov399" class="rated-user user-red">Golovanov399</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:41">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776651" href="?#comment-776651" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776651" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="10266" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776651"> <div class="moveup"> <div class="ttypography"><p>I like my solution in I more: <code>[36]Σ[80148078967894]Σ¡ÿ</code>. It uses fancy &quot;convert to base representation&quot; and &quot;title&quot; operators. Also it uses a shorter way to push a number onto stack :)</p><p>Also, was using quotes and/or escape-backslashes the unintended feature?</p></div> </div> </div> <div class="reply info"> <a class="comment-776651 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776651 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776651"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776664" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hello" style="position: relative;"> <img src='https://userpic.codeforces.org/156319/avatar/d3175cb4d9af736.jpg'/> </a> <div><a href="/profile/hello" title="Candidate Master hello" class="rated-user user-violet">hello</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776664" href="?#comment-776664" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776664" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="156319" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776664"> <div class="moveup"> <div class="ttypography"><p>For Problem F, I learned a lot from <a href="https://nemeth.aphtech.org/">https://nemeth.aphtech.org/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776664 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776664 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776664"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776665" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pedastrian57" style="position: relative;"> <img src='https://userpic.codeforces.org/1163197/avatar/7d26fc00c3d7f539.jpg'/> </a> <div><a href="/profile/pedastrian57" title="Candidate Master pedastrian57" class="rated-user user-violet">pedastrian57</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:46">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776665" href="?#comment-776665" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776665" class="CommentVoteFrame" data-commentRating="39" data-commentUserId="1163197" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+39</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776665"> <div class="moveup"> <div class="ttypography"><p>I think this tc should be added in E <br /> 4 4<br /> ...* <br /> ...* <br /> *...<br /> ....<br /> The correct output should be 1 according to the editorial , but some solutions (including tourist) is giving ans as 2</p></div> </div> </div> <div class="reply info"> <a class="comment-776665 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776665 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776665"> <li> <div class="comment"> <table class="comment-table" commentId="777141" commentParentId="776665"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Rook_Lift" style="position: relative;"> <img src='https://userpic.codeforces.org/1433566/avatar/a7fc097fc7cfaa0.jpg'/> </a> <div><a href="/profile/Rook_Lift" title="Specialist Rook_Lift" class="rated-user user-cyan">Rook_Lift</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/03/2021 09:32">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-777141" href="?#comment-777141" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776665" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="777141" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1433566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-777141"> <div class="moveup"> <div class="ttypography"><p>yes even my code outputs it as 1 and is AC </p></div> </div> </div> <div class="reply info"> <a class="comment-777141 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-777141 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-777141"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776682" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fdsafastwrqfas" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fdsafastwrqfas" title="Specialist fdsafastwrqfas" class="rated-user user-cyan">fdsafastwrqfas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:55">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776682" href="?#comment-776682" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776682" class="CommentVoteFrame" data-commentRating="158" data-commentUserId="1724795" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+158</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776682"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/1c/26/1c26aefdf48e4b7ca6161ff5539ba97639176c11.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div> </div> </div> <div class="reply info"> <a class="comment-776682 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776682 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776682"> <li> <div class="comment"> <table class="comment-table" commentId="776699" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ambersand" style="position: relative;"> <img src='https://userpic.codeforces.org/1280126/avatar/fceac4c3b6c8da8b.jpg'/> </a> <div><a href="/profile/Ambersand" title="Candidate Master Ambersand" class="rated-user user-violet">Ambersand</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776699" href="?#comment-776699" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776699" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1280126" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776699"> <div class="moveup"> <div class="ttypography"><p>So the April Fools round is also kind of an educational round...</p></div> </div> </div> <div class="reply info"> <a class="comment-776699 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776699 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776699"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776741" commentParentId="776682"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:31">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776741" href="?#comment-776741" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776682" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776741" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776741"> <div class="moveup"> <div class="ttypography"><p>There is one more step somewhere between 3 and 4: Braille is very commonly used in escape rooms, puzzle hunts, etc. — that's how I'm learning it :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776741"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776683" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/rotavirus" style="position: relative;"> <img src='https://userpic.codeforces.org/383901/avatar/dba9b8d07d2151be.jpg'/> </a> <div><a href="/profile/rotavirus" title="Master rotavirus" class="rated-user user-orange">rotavirus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776683" href="?#comment-776683" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776683" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="383901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776683"> <div class="moveup"> <div class="ttypography"><p>im excited Nicolette is an admin of tc alchemy progopedia</p></div> </div> </div> <div class="reply info"> <a class="comment-776683 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776683 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776683"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776689" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776689" href="?#comment-776689" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776689" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776689"> <div class="moveup"> <div class="ttypography"><p>Is there a problem in my code that I don't see?</p> <pre><code>x = str(input()) y = 0 for i in x: y += int(i) print(y) </code></pre><p>For some reason it fails on test 4 of DMCA.</p></div> </div> </div> <div class="reply info"> <a class="comment-776689 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776689 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776689"> <li> <div class="comment"> <table class="comment-table" commentId="776693" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776693" href="?#comment-776693" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776693"> <div class="moveup"> <div class="ttypography"><p>You need to put only single digit answer<br /> for example at 3689<br /> 3+6+8+9 = 26<br /> now you need to do :<br /> 2+6 = 8<br /> Therefore 8 is the answer and not 26.<br /></p></div> </div> </div> <div class="reply info"> <a class="comment-776693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776693"> <li> <div class="comment"> <table class="comment-table" commentId="776713" commentParentId="776693"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/FyodorV" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/FyodorV" title="Newbie FyodorV" class="rated-user user-gray">FyodorV</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776713" href="?#comment-776713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776713" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="2008697" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776713"> <div class="moveup"> <div class="ttypography"><p>I'm such a dumbass.</p></div> </div> </div> <div class="reply info"> <a class="comment-776713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776713"> <li> <div class="comment"> <table class="comment-table" commentId="776732" commentParentId="776713"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/chilliagon" style="position: relative;"> <img src='https://userpic.codeforces.org/1854727/avatar/522040a3bfee78a.jpg'/> </a> <div><a href="/profile/chilliagon" title="Newbie chilliagon" class="rated-user user-gray">chilliagon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776732" href="?#comment-776732" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776732" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1854727" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776732"> <div class="moveup"> <div class="ttypography"><p>lol Even I didnot notice it during contest. I dont even know how DMCA is related to Digital Sum!</p></div> </div> </div> <div class="reply info"> <a class="comment-776732 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776732 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776732"> <li> <div class="comment"> <table class="comment-table" commentId="776761" commentParentId="776732"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:48">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776761" href="?#comment-776761" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776732" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776761" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776761"> <div class="moveup"> <div class="ttypography"><p>Digital [millenium] Calculation [act]. And you're asked about a root in the statement. Add the two words together, digital root.</p></div> </div> </div> <div class="reply info"> <a class="comment-776761 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776761 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776761"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776700" commentParentId="776689"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:05">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776700" href="?#comment-776700" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776689" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776700" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776700"> <div class="moveup"> <div class="ttypography"><p>It gives <code>18</code> for <code>99</code>. <code>9</code> is the correct answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776700 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776700 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776700"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776690" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/-senshi-" style="position: relative;"> <img src='https://userpic.codeforces.org/1499416/avatar/33fc48f8e0499456.jpg'/> </a> <div><a href="/profile/-senshi-" title="Expert -senshi-" class="rated-user user-blue">-senshi-</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 19:58">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776690" href="?#comment-776690" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776690" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1499416" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+3</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776690"> <div class="moveup"> <div class="ttypography"><p>For problem F, after around 20 mins of head scratching, <a href="http://abcbraille.com/braille">this</a> website saved me :)</p></div> </div> </div> <div class="reply info"> <a class="comment-776690 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776690 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776690"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776691" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DoubleAS" style="position: relative;"> <img src='https://userpic.codeforces.org/1473693/avatar/9abc76dcdccc56ae.jpg'/> </a> <div><a href="/profile/DoubleAS" title="Pupil DoubleAS" class="rated-user user-green">DoubleAS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:00">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776691" href="?#comment-776691" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776691" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="1473693" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776691"> <div class="moveup"> <div class="ttypography"><p>To be honest I didn't like the problem set. I don't know how everyone other than me is liking it much. Expected better problems to make everyone fool! :&quot;3</p></div> </div> </div> <div class="reply info"> <a class="comment-776691 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776691 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776691"> <li> <div class="comment"> <table class="comment-table" commentId="776695" commentParentId="776691"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/WolfBlue" style="position: relative;"> <img src='https://userpic.codeforces.org/568741/avatar/2d12204e3a43ec9a.jpg'/> </a> <div><a href="/profile/WolfBlue" title="Candidate Master WolfBlue" class="rated-user user-violet">WolfBlue</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:04">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776695" href="?#comment-776695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776691" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="568741" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+1</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776695"> <div class="moveup"> <div class="ttypography"><p>Yeah, not enough data structure problems, they were all ad-hoc</p></div> </div> </div> <div class="reply info"> <a class="comment-776695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776695"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776709" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776709" href="?#comment-776709" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776709" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776709" class="CommentVoteFrame" data-commentRating="52" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+52</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776709"> <div class="moveup"> <div class="ttypography"><p>Here's a (somewhat) simpler solution to H. Open the file as binary. It's mostly unreadable, but there's some clearly visible text like <code>n=11</code>, <code>a(n)</code>, <code>b(n)</code>, <code>TODO Change - to +</code> and <code>c=a(i)-b(i)</code>. There are also some two-digit numbers with commas nearby. If you remove all non-printable characters, you get <code>44,12,49,17,10,25,18,17,24,25,20</code> and <code>55,99,61,99,91,90,98,30,25,30,29</code>, which you suppose to be the arrays <code>a</code> and <code>b</code>, especially given that they both contain 11 numbers. After that just calculate the sum and get the answer.</p></div> </div> </div> <div class="reply info"> <a class="comment-776709 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776709 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776709"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776714" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:14">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776714" href="?#comment-776714" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776714" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776714"> <div class="moveup"> <div class="ttypography"><p>Here's something that was done wrong in this round: the title of I shouldn't have been translated to Russian, like you did with problem D. The language is named 'seriously', not 'серьезно'.</p></div> </div> </div> <div class="reply info"> <a class="comment-776714 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776714 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776714"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776716" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pichulia" style="position: relative;"> <img src='https://userpic.codeforces.org/13019/avatar/3015e95c4fc98fa4.jpg'/> </a> <div><a href="/profile/pichulia" title="Grandmaster pichulia" class="rated-user user-red">pichulia</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:15">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776716" href="?#comment-776716" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776716" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="13019" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+8</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776716"> <div class="moveup"> <div class="ttypography"><p>Even <code>xenodrome</code> is NOT fancy-sounding word :(</p></div> </div> </div> <div class="reply info"> <a class="comment-776716 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776716 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776716"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776734" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Swistakk" style="position: relative;"> <img src='https://userpic.codeforces.org/54086/avatar/9228a341f35b8318.jpg'/><img title='Badge of honor for supporting Codeforces on its 10th anniversary' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/Swistakk" title="International Grandmaster Swistakk" class="rated-user user-red">Swistakk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:26">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776734" href="?#comment-776734" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776734" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="54086" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776734"> <div class="moveup"> <div class="ttypography"><p>I couldn't find anything online for Z80. &quot;Z80 emulator&quot; only gave me some garbage results and I am impressed by googling skills of people that were able to find anything helpful that way. And even if I succeeded in that I would need to execute some completely random commands there I see (these BREAK, LIST, RUN, wtf?). What I did was just to stare at the text dump and figuring out what it does was pretty easy from that.</p></div> </div> </div> <div class="reply info"> <a class="comment-776734 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776734 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776734"> <li> <div class="comment"> <table class="comment-table" commentId="776748" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dorijanlendvaj" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dorijanlendvaj" title="Legendary Grandmaster dorijanlendvaj" class="rated-user user-legendary"><span class="legendary-user-first-letter">d</span>orijanlendvaj</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:37">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776748" href="?#comment-776748" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776748" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776748" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="79946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776748"> <div class="moveup"> <div class="ttypography"><p>Googling the problem name is more useful than &quot;Z80 emulator&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-776748 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776748 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776748"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="776763" commentParentId="776734"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:49">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776763" href="?#comment-776763" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776734" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776763" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776763"> <div class="moveup"> <div class="ttypography"><p>Z80 is a processor, it's as if you googled 'x86 emulator'. You were actually looking for a ZX Spectrum emulator. BREAK is not a command but a key. LIST and RUN are some standard BASIC commands, almost every BASIC dialect has them.</p><p>Doesn't make the problem any better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-776763 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776763 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776763"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776735" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coder_redefined" style="position: relative;"> <img src='https://userpic.codeforces.org/1220743/avatar/671b31834461ea0f.jpg'/> </a> <div><a href="/profile/coder_redefined" title="Pupil coder_redefined" class="rated-user user-green">coder_redefined</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:28">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776735" href="?#comment-776735" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776735" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1220743" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776735"> <div class="moveup"> <div class="ttypography"><p>did anyone feel the answer for I is Whitespace Language XD ?? Completely went down that rabbit hole and I feel like I am the biggest April fool.</p></div> </div> </div> <div class="reply info"> <a class="comment-776735 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776735 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776735"> <li> <div class="comment"> <table class="comment-table" commentId="776766" commentParentId="776735"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:51">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776766" href="?#comment-776766" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776735" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776766" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776766"> <div class="moveup"> <div class="ttypography"><p>Hey, same here. But then I tried <code>123</code> just to make sure and <em>boom</em>, no, not whitespace. I spent the following 60 minutes checking some commands like <code>+</code> and <code>*</code> to check if it's a stack-based language, <code>H</code> and <code>Q</code> for hello world and quine to check if it's a code golfing language, etc. I didn't expect it to be some random esolang we're supposed to guess from English problem title (Russian translation made it much harder to figure out 'Seriously' is a name, not a word).</p></div> </div> </div> <div class="reply info"> <a class="comment-776766 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776766 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776766"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776767" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 20:54">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776767" href="?#comment-776767" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776767" class="CommentVoteFrame" data-commentRating="15" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+15</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776767"> <div class="moveup"> <div class="ttypography"><p>What was the 'undocumented language feature' in I that you disabled, by the way?</p></div> </div> </div> <div class="reply info"> <a class="comment-776767 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776767 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776767"> <li> <div class="comment"> <table class="comment-table" commentId="776776" commentParentId="776767"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Nickolas" style="position: relative;"> <img src='https://userpic.codeforces.org/15862/avatar/3812c6d62c7e7a0b.jpg'/> </a> <div><a href="/profile/Nickolas" title="Expert Nickolas" class="rated-user user-blue">Nickolas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:08">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776776" href="?#comment-776776" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776767" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776776" class="CommentVoteFrame" data-commentRating="-10" data-commentUserId="15862" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-10</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776776"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> just printing the message... I was happy with pretty much any other way to output the message (people who solved this problem all used different approaches, neither of them using mine), but this one takes it a bit too far even for the April Fools Day Contest — and <code>&quot;</code> is not supposed to do any printing :-)</p></div> </div> </div> <div class="reply info"> <a class="comment-776776 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776776 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776776"> <li> <div class="comment"> <table class="comment-table" commentId="776794" commentParentId="776776"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:17">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776794" href="?#comment-776794" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776776" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776794" class="CommentVoteFrame" data-commentRating="36" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+36</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776794"> <div class="moveup"> <div class="ttypography"><p><code>&quot;Seriously&quot;</code> is a completely valid solution. <code>&quot;Seriously&quot;</code> on itself pushes the string onto stack. When the program ends, the stack is printed to the terminal. As there's only one string in the stack, it gets printed.</p><p>What part of that is undocumented?</p></div> </div> </div> <div class="reply info"> <a class="comment-776794 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776794 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776794"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776789" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Analy7iKAlEngine" style="position: relative;"> <img src='https://userpic.codeforces.org/1662500/avatar/a48442affef87ebb.jpg'/> </a> <div><a href="/profile/Analy7iKAlEngine" title="Newbie Analy7iKAlEngine" class="rated-user user-gray">Analy7iKAlEngine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:13">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776789" href="?#comment-776789" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> <span style="" commentId="776789" revisionCount="2" revision="2"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">2</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="776789" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662500" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776789"> <div class="moveup"> <div class="ttypography"><p>What was wrong with this solution if you guys don't mind, Prob B: <a href="https://codeforces.com/contest/1505/submission/111717549">https://codeforces.com/contest/1505/submission/111717549</a> Edit: Didn't run my code on my machine for this contest. It's buggy</p></div> </div> </div> <div class="reply info"> <a class="comment-776789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776789"> <li> <div class="comment"> <table class="comment-table" commentId="776795" commentParentId="776789"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/imachug" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/imachug" title="International Master imachug" class="rated-user user-orange">imachug</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 21:18">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776795" href="?#comment-776795" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776789" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776795" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="562886" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776795"> <div class="moveup"> <div class="ttypography"><p>You don't need <code>i *= 10</code>. You also need to wrap the code in a <code>while(num &gt; 9)</code> loop.</p><p>But a much better solution is to print <code>(n - 1) % 9 + 1</code>.</p></div> </div> </div> <div class="reply info"> <a class="comment-776795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776795"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776823" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aksingh123" style="position: relative;"> <img src='https://userpic.codeforces.org/1646272/avatar/5820e39f18d87d66.jpg'/> </a> <div><a href="/profile/aksingh123" title="Newbie aksingh123" class="rated-user user-gray">aksingh123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:19">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776823" href="?#comment-776823" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776823" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1646272" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776823"> <div class="moveup"> <div class="ttypography"><p>why -&gt; i did not use fflush in my code for interaction problem and i got ac link-&gt;<a href="https://codeforces.com/contest/1505/submission/111731883">https://codeforces.com/contest/1505/submission/111731883</a></p></div> </div> </div> <div class="reply info"> <a class="comment-776823 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776823 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776823"> <li> <div class="comment"> <table class="comment-table" commentId="776832" commentParentId="776823"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deneribeiro10" style="position: relative;"> <img src='https://userpic.codeforces.org/1461039/avatar/dfad673833b00063.jpg'/> </a> <div><a href="/profile/deneribeiro10" title="Expert deneribeiro10" class="rated-user user-blue">deneribeiro10</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/01/2021 22:56">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776832" href="?#comment-776832" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-776823" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776832" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1461039" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776832"> <div class="moveup"> <div class="ttypography"><p>endl = &quot;\n&quot; + flush</p></div> </div> </div> <div class="reply info"> <a class="comment-776832 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776832 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776832"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776861" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AnandOza" style="position: relative;"> <img src='https://userpic.codeforces.org/80302/avatar/adfa6befa3f8cfe2.jpg'/> </a> <div><a href="/profile/AnandOza" title="Grandmaster AnandOza" class="rated-user user-red">AnandOza</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 01:03">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776861" href="?#comment-776861" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="80302" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776861"> <div class="moveup"> <div class="ttypography"><p>Hi, can you enable uphacking?</p></div> </div> </div> <div class="reply info"> <a class="comment-776861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776861"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="776880" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cantThinkOfGoodUsername" style="position: relative;"> <img src='https://userpic.codeforces.org/1357353/avatar/233f433160257248.jpg'/> </a> <div><a href="/profile/cantThinkOfGoodUsername" title="Expert cantThinkOfGoodUsername" class="rated-user user-blue">cantThinkOfGoodUsername</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/02/2021 05:36">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-776880" href="?#comment-776880" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="776880" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1357353" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-776880"> <div class="moveup"> <div class="ttypography"><p>In A, printing &quot;NO&quot; a large number of times seems to work. (without taking any input)</p></div> </div> </div> <div class="reply info"> <a class="comment-776880 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-776880 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-776880"> </ul> </div> <br/> <div id="editBox-97591" style="width:50em;display:none;"> <div class="previewBody" style="border: 1px solid #d4d4d4; margin-bottom: 0.5em; padding: 0.25em; display:none;">&nbsp;</div> <div style="width: 1px">&nbsp;</div> <div class="commentLocale" style="position: relative; top: 0.5em;left:4px;display: none;"> <input type="radio" name="locale" value="en"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In English</span> <input style="margin-left:1em" type="radio" name="locale" value="ru"><span style="font-size: 1.2rem;position: relative; bottom: 3px;">In Russian</span> </div> <textarea data-drafts-id="CommentReplyFrame" class="wysiwyg" name="editContent" rows="20" style="width:99%;"></textarea> <div class="error error__content"></div> <div style="text-align:center;"> <input type="button" name="preview" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Preview"/> <input type="button" name="save" style="padding: 0.25em 1em; margin-top: 1em; min-width: 6.5em;" value="Save"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { var firstPreview97591 = true; var lastPreviewContent97591 = ''; if (!window.moveCommentRevision) { moveCommentRevision = function(e, dir) { var p = e.parent(); var revisionCount = parseInt(p.attr("revisionCount")); var revision = parseInt(p.attr("revision")); var next = revision + dir; var commentId = p.attr("commentId"); if (next >= 1 && next <= revisionCount) { $.post( "/data/comment-data", {action: "revision", commentId: commentId, revision: next}, function(json) { if (json.success == "true") { var parentDiv = e; while (parentDiv !== null && (parentDiv[0].nodeName.toLowerCase() !== "td" || !parentDiv.hasClass("right"))) { parentDiv = parentDiv.parent(); } if (parentDiv === null) { return; } parentDiv.find("div.comment-content-" + commentId + " .moveup").html(json.content); Codeforces.setupSpoilers(parentDiv.find("div.comment-content-" + commentId + " .moveup")); p.attr("revision", next); p.find("span.revision").text(next); if (next == 1) { p.find("a.leftRevision").css("visibility", "hidden"); } else { p.find("a.leftRevision").css("visibility", "visible"); } if (next == revisionCount) { p.find("a.rightRevision").css("visibility", "hidden"); } else { p.find("a.rightRevision").css("visibility", "visible"); } window.updateTypography(); MathJax.Hub.Typeset(); } else { alert(e.error); } }, "json" ); } }; } $("div[commentableId=97591] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=97591] a.rightRevision").click(function () { window.moveCommentRevision($(this), +1); return false; }); }); </script> <script src="//codeforces.org/s/81027/js/swfobject-2.2.min.js" type="text/javascript"></script> <script src="//codeforces.org/s/81027/js/ftaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { if (window.evercookie) { var ec = new evercookie({ history: false, silverlight: false, baseurl: '', asseturi: '/assets', phpuri: '/2fdcd78', pngPath: '/eps', etagPath: '/ees', cachePath: '/ecs' }); var randomNumber = function () { return Math.random().toString(36).substr(2); }; var randomToken = function () { return (randomNumber() + randomNumber()).substring(0, 18); }; window._ftaa = ""; ec.get("70a7c28f3de", function (value) { window._ftaa = value; if (!window._ftaa) { window._ftaa = randomToken(); ec.set("70a7c28f3de", window._ftaa); } $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); } else { window._ftaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script src="//codeforces.org/s/81027/js/bfaa.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var fpCallback = function() { Fingerprint2.get({}, function(components) { window._bfaa = Fingerprint2.x64hash128(components.map(function (pair) { return pair.value }).join(), 31); $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); }); }; if (typeof Fingerprint2 !== 'undefined') { if (window.requestIdleCallback) { requestIdleCallback(fpCallback) } else { setTimeout(fpCallback, 500) } } else { window._bfaa = "n/a"; $.post("/data/empty", {bfaa: window._bfaa, ftaa: window._ftaa}); } }); </script> <script type="text/javascript"> $(document).ready(function () { $("a.new-root-comment").click(function () { window.location = "/enter"; return false; }); $(".comment-table .reply a").click(function () { window.location = "/enter"; return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { $(".vote-for-comment").mouseover(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.find("img").attr("popacity", vote.find("img").css("opacity")); vote.find("img").css("opacity", "1.0"); } }); $(".vote-for-comment").mouseout(function () { var vote = $(this); var direction = vote.attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; if (direction == 1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } if (direction == -1 && !ownComment) { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown-blue.png"); vote.find("img").css("opacity", vote.find("img").attr("popacity")); } }); $(".vote-for-comment").click(function () { var vote = $(this); var commentId = $(this).parent().attr("commentid"); var commentRating = $(this).parent().attr("data-commentRating"); var direction = $(this).attr("voteDirection"); var commentUserId = $(this).parent().attr("data-commentUserId"); var ownComment = false; $.post("/data/comment/vote", {commentId: commentId, _tta: Codeforces.tta(), vote: direction, commentRating: commentRating}, function(data) { if (direction != 0 && !ownComment && data["success"] == "true") { vote.parent().find(".vote-for-comment").attr("voteDirection", 0); if (direction == 1) vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-voteup.png"); else { vote.find("img").attr("src", "//codeforces.org/s/81027/images/actions/comment-votedown.png"); vote.closest(".CommentVoteFrame").find(".ComplaintFrame").css("display", "inline-block"); } vote.find("img").attr("popacity", "1.0"); vote.find("img").css("opacity", "1.0"); vote.parent().find(".commentRating").html(data["commentRating"]); } Codeforces.showMessage(data["message"]); }, "json"); return false; }); $(".negative-comment-vote").closest(".comment-table").addClass("comment-bad"); $(".troll-comment-vote").closest(".comment").css("display", "none"); $(".too-negative-comment-vote").closest(".comment-table").each(function () { var e = $(this); e.addClass("comment-too-bad"); var commentId = e.attr("commentId"); $("<div class='bad-comment-replacement ttypography'>The comment is hidden because of too negative feedback, click <a href=# class=show-bad-comment-link>here</a> to view it</div>").appendTo( e.find(".right") ); e.find(".comment-content").hide(); e.find(".show-bad-comment-link").click(function () { e.find(".comment-content").show(); e.find(".bad-comment-replacement").hide(); return false; }); }); }); </script> </div> <style type="text/css"> .new-comments-box { padding: 0.5em; width: 22px; font-size: 1.3rem; font-weight: bold !important; position: fixed; top: 40%; right: 0; opacity: 0.2; color: white; text-align: center; border: 1px solid #222; background-color: #888 !important; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .new-comments-box:hover { opacity: 1; } .new-comments-box .dir:hover { background: #3B5998 !important; cursor: pointer; } </style> <div class="new-comments-box" data-position="outside" data-index="-1" style="display: none;"> <div class="up dir" title="Ctrl+Up">&uarr;<hr/> </div> <div class="info" title="New comments"></div> <div class="down dir" title="Ctrl+Down"> <hr/>&darr; </div> </div> <script> $(".show-archived-checkbox").change(function () { const checked = $(this).is(":checked"); $.post("/data/comment-data", {action: "setShowArchived", checked}, function (json) { if (json["success"] !== "true") { alert(json["error"]); } else { if (checked) { Codeforces.reloadAndShowMessage("Archived comments are now displayed") } else { Codeforces.reloadAndShowMessage("Archived comments are no longer displayed") } } }); return false; }); function gotoComment(direction) { var box = $(".new-comments-box"); var index = parseInt(box.attr("data-index")); if (index == -1) index = 0; else index = Math.max(0, Math.min(parseInt(box.find(".info").text()) - 1, index + direction)); box.attr("data-index", index); var comment = $($(".comment .highlight-blue[commentId]").get(index)); $('html, body').animate({ 'scrollTop': Math.max(0, comment.offset().top - ($(window).height() - comment.height()) / 2) }); return false; } $(".new-comments-box .down").click(function () { return gotoComment(1); }); $(".new-comments-box .up").click(function () { return gotoComment(-1); }); $(document).keydown(function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey) { if (code == 38 || code == 40) { gotoComment(code - 39); } } }); var newCommentCount = $(".comment .highlight-blue[commentId]").length; if (newCommentCount > 0) { $(".new-comments-box .info").text(newCommentCount); $(".new-comments-box").show(); } $('table.comment-table').mouseenter(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").addClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); $('table.comment-table').mouseleave(function () { var comment = $(this); var cnt = 0; while (true) { var id = comment.attr("commentId"); var parentId = comment.attr("commentParentId"); comment.find(".comment-indent-holder:first .comment-no-indent").removeClass("comment-indent"); if (parentId == -1) { break; } comment = $("table.comment-table[commentId=" + parentId + "]"); } return false; }); </script> <script> function adjustTopicComplainFrames() { let topicIds = []; $(".has-topic-id").each(function () { const $this = $(this); const topicId = $this.attr("topicId"); if (topicId) { topicIds.push(topicId); } }); $.post("/data/topics", { action: "findComplainableTopicIds", topicIds: topicIds.join(",") }, function (json) { if (json["success"] === "true") { for (const topicId of json["complainableTopicIds"].split(",")) { $(".has-topic-id[topicId=" + topicId + "]").each(function () { $(this).find(".meta .ComplaintFrame").css("display", "inline-block"); }); } } }, "json"); } $(function () { adjustTopicComplainFrames(); }) </script> <script type="text/javascript"> $(document).ready(function () { $(".topic-vote-up-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-89866").click(function () { $.post("/data/topic/vote", {topicId: 89866, _tta: Codeforces.tta(), topicRevisionId: 222156, vote: -1}, function(data) { Codeforces.showMessage(data); adjustTopicComplainFrames(); }, "json"); return false; }); }); </script> </div> </div> </div> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Mike Mirzayanov</div> <div>The only programming contests Web 2.0 platform</div> <div>Server time: <span class="format-timewithseconds" data-locale="en">Oct/07/2023 22:32:36</span> (h1).</div> <div>Desktop version, switch to <a rel="nofollow" class="switchToMobile" href="?mobile=true">mobile version</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> Supported by </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/81027/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/en/"><img style="width: 120px;" src="//codeforces.org/s/81027/images/itmo_small_en-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> User lists <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/81027/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/81027/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Matches: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">No items<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-81027.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8128922b2ad80056',t:'MTY5NjcwNzE1Ni4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1506A
1506
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$$$ столбцов. Он заметил, что в каждой ячейке таблицы записан ее номер, полученный по следующему алгоритму <span class="tex-font-style-bf">«по столбцам»</span>: </p><ul> <li> ячейки занумерованы начиная с единицы; </li><li> ячейки нумеруются слева направо по столбцам, а внутри каждого столбца сверху вниз; </li><li> номер каждой ячейки — целое число, на единицу большее, чем номер предыдущей ячейки. </li></ul><p>Например, если $$$n = 3$$$ и $$$m = 5$$$, то таблица будет занумерована следующим образом:</p><p>$$$$$$ \begin{matrix} 1 &amp; 4 &amp; 7 &amp; 10 &amp; 13 \\ 2 &amp; 5 &amp; 8 &amp; 11 &amp; 14 \\ 3 &amp; 6 &amp; 9 &amp; 12 &amp; 15 \\ \end{matrix} $$$$$$</p><p>Однако, Поликарп считает такую нумерацию неудобной. Ему нравится нумерация <span class="tex-font-style-bf">«по строкам»</span>: </p><ul> <li> ячейки занумерованы начиная с единицы; </li><li> ячейки нумеруются сверху вниз по строкам, а внутри каждой строки слева направо; </li><li> номер каждой ячейки — целое число, на единицу большее, чем номер предыдущей ячейки. </li></ul><p>Например, если $$$n = 3$$$ и $$$m = 5$$$, то Поликарпу нравится следующая нумерация таблицы: $$$$$$ \begin{matrix} 1 &amp; 2 &amp; 3 &amp; 4 &amp; 5 \\ 6 &amp; 7 &amp; 8 &amp; 9 &amp; 10 \\ 11 &amp; 12 &amp; 13 &amp; 14 &amp; 15 \\ \end{matrix} $$$$$$</p><p>У Поликарпа мало времени, поэтому он просит вас узнать, какой был бы номер ячейки в нумерации <span class="tex-font-style-bf">«по строкам»</span>, если в нумерации <span class="tex-font-style-bf">«по столбцам»</span> ячейка имеет номер $$$x$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки, в которой находится три целых числа $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le x \le n \cdot m$$$), $$$n$$$ и $$$m$$$ — количество строк и столбцов в таблице, и $$$x$$$ — номер ячейки.</p><p>Обратите внимание, что числа в некоторых наборах входных данных не влезают в $$$32$$$-битный целочисленный тип, поэтому вы должны использовать как минимум $$$64$$$-битный целочисленный тип вашего языка программирования.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — номер ячейки в нумерации <span class="tex-font-style-bf">«по строкам»</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 2 2 3 3 5 11 100 100 7312 1000000 1000000 1000000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 9 1174 1000000000000 </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="6e43f5e2bf186f52787452a59f652182"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6e43f5e2bf186f52787452a59f652182'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='6e43f5e2bf186f52787452a59f652182'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6e43f5e2bf186f52787452a59f652182'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='6e43f5e2bf186f52787452a59f652182'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935559"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6e43f5e2bf186f52787452a59f652182'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935559"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_075186b9245c1dc92c31589887654262f2fc0680"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$ столбцов. Он заметил, что в каждой ячейке таблицы записан ее номер, полученный по следующему алгоритму <span class="tex-font-style-bf">«по столбцам»</span>: </p><ul> <li> ячейки занумерованы начиная с единицы; </li><li> ячейки нумеруются слева направо по столбцам, а внутри каждого столбца сверху вниз; </li><li> номер каждой ячейки — целое число, на единицу большее, чем номер предыдущей ячейки. </li></ul><p>Например, если $$$n = 3$$$ и $$$m = 5$$$, то таблица будет занумерована следующим образом:</p><p>$$$$$$ \begin{matrix} 1 &amp; 4 &amp; 7 &amp; 10 &amp; 13 \\ 2 &amp; 5 &amp; 8 &amp; 11 &amp; 14 \\ 3 &amp; 6 &amp; 9 &amp; 12 &amp; 15 \\ \end{matrix} $$$$$$</p><p>Однако, Поликарп считает такую нумерацию неудобной. Ему нравится нумерация <span class="tex-font-style-bf">«по строкам»</span>: </p><ul> <li> ячейки занумерованы начиная с единицы; </li><li> ячейки нумеруются сверху вниз по строкам, а внутри каждой строки слева направо; </li><li> номер каждой ячейки — целое число, на единицу большее, чем номер предыдущей ячейки. </li></ul><p>Например, если $$$n = 3$$$ и $$$m = 5$$$, то Поликарпу нравится следующая нумерация таблицы: $$$$$$ \begin{matrix} 1 &amp; 2 &amp; 3 &amp; 4 &amp; 5 \\ 6 &amp; 7 &amp; 8 &amp; 9 &amp; 10 \\ 11 &amp; 12 &amp; 13 &amp; 14 &amp; 15 \\ \end{matrix} $$$$$$</p><p>У Поликарпа мало времени, поэтому он просит вас узнать, какой был бы номер ячейки в нумерации <span class="tex-font-style-bf">«по строкам»</span>, если в нумерации <span class="tex-font-style-bf">«по столбцам»</span> ячейка имеет номер $$$x$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки, в которой находится три целых числа $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le x \le n \cdot m$$$), $$$n$$$ и $$$m$$$ — количество строк и столбцов в таблице, и $$$x$$$ — номер ячейки.</p><p>Обратите внимание, что числа в некоторых наборах входных данных не влезают в $$$32$$$-битный целочисленный тип, поэтому вы должны использовать как минимум $$$64$$$-битный целочисленный тип вашего языка программирования.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — номер ячейки в нумерации <span class="tex-font-style-bf">«по строкам»</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 1 1 2 2 3 3 5 11 100 100 7312 1000000 1000000 1000000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 9 1174 1000000000000 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:20</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf49e84716cb',t:'MTY5NjY2NzA2MC45NDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1506B
1506
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>Вам заданы число $$$k$$$ и строка $$$s$$$ длины $$$n$$$, состоящая из символов '<span class="tex-font-style-tt">.</span>' и '<span class="tex-font-style-tt">*</span>'. Вы хотите заменить некоторые из символов '<span class="tex-font-style-tt">*</span>' на символы '<span class="tex-font-style-tt">x</span>', чтобы были выполнены следующее условия: </p><ul> <li> Самый первый символ '<span class="tex-font-style-tt">*</span>' в исходной строке должен быть заменен на '<span class="tex-font-style-tt">x</span>'; </li><li> Самый последний символ '<span class="tex-font-style-tt">*</span>' в исходной строке должен быть заменен на '<span class="tex-font-style-tt">x</span>'; </li><li> Расстояние между двумя соседними замененными символами '<span class="tex-font-style-tt">x</span>' не должно превосходить $$$k$$$ (более формально, если вы заменили символы на позициях $$$i$$$ и $$$j$$$ ($$$i &lt; j$$$) и на позициях $$$[i+1, j-1]$$$ нет символа '<span class="tex-font-style-tt">x</span>', то $$$j-i$$$ должно быть не больше $$$k$$$). </li></ul><p>Например, если $$$n=7$$$, $$$s=$$$<span class="tex-font-style-tt">.**.***</span> и $$$k=3$$$, то вы следующие строки будут удовлетворять условиям выше: </p><ul> <li> <span class="tex-font-style-tt">.xx.*xx</span>; </li><li> <span class="tex-font-style-tt">.x*.x*x</span>; </li><li> <span class="tex-font-style-tt">.xx.xxx</span>. </li></ul> Но, например, следующие строки удовлетворять условиям не будут: <ul> <li> <span class="tex-font-style-tt">.**.*xx</span> (самый первый символ '<span class="tex-font-style-tt">*</span>' должен быть заменен на '<span class="tex-font-style-tt">x</span>'); </li><li> <span class="tex-font-style-tt">.x*.xx*</span> (самый последний символ '<span class="tex-font-style-tt">*</span>' должен быть заменен на '<span class="tex-font-style-tt">x</span>'); </li><li> <span class="tex-font-style-tt">.x*.*xx</span> (расстояние между символами на позициях $$$2$$$ и $$$6$$$ больше $$$k=3$$$). </li></ul><p>Для заданных $$$n$$$, $$$k$$$ и $$$s$$$ найдите минимальное количество символов '<span class="tex-font-style-tt">*</span>', которые необходимо заменить на символы '<span class="tex-font-style-tt">x</span>', чтобы были выполнены условия выше.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 500$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 50$$$).</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длины $$$n$$$, состоящую из символов '<span class="tex-font-style-tt">.</span>' и '<span class="tex-font-style-tt">*</span>'.</p><p>Гарантируется, что в строке $$$s$$$ есть хотя бы один символ '<span class="tex-font-style-tt">*</span>'.</p><p>Гарантируется, что расстояние между любыми двумя соседними символами '<span class="tex-font-style-tt">*</span>' не превосходит $$$k$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество символов '<span class="tex-font-style-tt">*</span>', которые необходимо заменить на символы '<span class="tex-font-style-tt">x</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 7 3 .**.*** 5 1 ..*.. 5 2 *.*.* 3 2 *.* 1 1 * </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 3 2 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e9caa9fad37f82a94ff122a1a3822c5a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e9caa9fad37f82a94ff122a1a3822c5a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='e9caa9fad37f82a94ff122a1a3822c5a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e9caa9fad37f82a94ff122a1a3822c5a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='e9caa9fad37f82a94ff122a1a3822c5a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935560"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e9caa9fad37f82a94ff122a1a3822c5a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935560"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5a84e464e3ec135f57afe9b2caca04d19a774f09"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Вам заданы число $$$k$$$ и строка $$$s$$$ длины $$$n$$$, состоящая из символов '<span class="tex-font-style-tt">.</span>' и '<span class="tex-font-style-tt">*</span>'. Вы хотите заменить некоторые из символов '<span class="tex-font-style-tt">*</span>' на символы '<span class="tex-font-style-tt">x</span>', чтобы были выполнены следующее условия: </p><ul> <li> Самый первый символ '<span class="tex-font-style-tt">*</span>' в исходной строке должен быть заменен на '<span class="tex-font-style-tt">x</span>'; </li><li> Самый последний символ '<span class="tex-font-style-tt">*</span>' в исходной строке должен быть заменен на '<span class="tex-font-style-tt">x</span>'; </li><li> Расстояние между двумя соседними замененными символами '<span class="tex-font-style-tt">x</span>' не должно превосходить $$$k$$$ (более формально, если вы заменили символы на позициях $$$i$$$ и $$$j$$$ ($$$i &lt; j$$$) и на позициях $$$[i+1, j-1]$$$ нет символа '<span class="tex-font-style-tt">x</span>', то $$$j-i$$$ должно быть не больше $$$k$$$). </li></ul><p>Например, если $$$n=7$$$, $$$s=$$$<span class="tex-font-style-tt">.**.***</span> и $$$k=3$$$, то вы следующие строки будут удовлетворять условиям выше: </p><ul> <li> <span class="tex-font-style-tt">.xx.*xx</span>; </li><li> <span class="tex-font-style-tt">.x*.x*x</span>; </li><li> <span class="tex-font-style-tt">.xx.xxx</span>. </li></ul> Но, например, следующие строки удовлетворять условиям не будут: <ul> <li> <span class="tex-font-style-tt">.**.*xx</span> (самый первый символ '<span class="tex-font-style-tt">*</span>' должен быть заменен на '<span class="tex-font-style-tt">x</span>'); </li><li> <span class="tex-font-style-tt">.x*.xx*</span> (самый последний символ '<span class="tex-font-style-tt">*</span>' должен быть заменен на '<span class="tex-font-style-tt">x</span>'); </li><li> <span class="tex-font-style-tt">.x*.*xx</span> (расстояние между символами на позициях $$$2$$$ и $$$6$$$ больше $$$k=3$$$). </li></ul><p>Для заданных $$$n$$$, $$$k$$$ и $$$s$$$ найдите минимальное количество символов '<span class="tex-font-style-tt">*</span>', которые необходимо заменить на символы '<span class="tex-font-style-tt">x</span>', чтобы были выполнены условия выше.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 500$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 50$$$).</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длины $$$n$$$, состоящую из символов '<span class="tex-font-style-tt">.</span>' и '<span class="tex-font-style-tt">*</span>'.</p><p>Гарантируется, что в строке $$$s$$$ есть хотя бы один символ '<span class="tex-font-style-tt">*</span>'.</p><p>Гарантируется, что расстояние между любыми двумя соседними символами '<span class="tex-font-style-tt">*</span>' не превосходит $$$k$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество символов '<span class="tex-font-style-tt">*</span>', которые необходимо заменить на символы '<span class="tex-font-style-tt">x</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 7 3 .**.*** 5 1 ..*.. 5 2 *.*.* 3 2 *.* 1 1 * </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 3 2 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:22</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf52986576ad',t:'MTY5NjY2NzA2Mi4yOTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1100"]
1506C
1506
C
ru
C. Двусторонние строки
<div class="problem-statement"><div class="header"><div class="title">C. Двусторонние строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы строки $$$a$$$ и $$$b$$$, состоящие из строчных букв латинского алфавита. Вы можете сделать произвольное число следующих операций в произвольном порядке: </p><ul> <li> если $$$|a| &gt; 0$$$ (длина строки $$$a$$$ больше нуля), удалить первый символ строки $$$a$$$, то есть заменить $$$a$$$ на $$$a_2 a_3 \ldots a_n$$$; </li><li> если $$$|a| &gt; 0$$$, удалить последний символ строки $$$a$$$, то есть заменить $$$a$$$ на $$$a_1 a_2 \ldots a_{n-1}$$$; </li><li> если $$$|b| &gt; 0$$$ (длина строки $$$b$$$ больше нуля), удалить первый символ строки $$$b$$$, то есть заменить $$$b$$$ на $$$b_2 b_3 \ldots b_n$$$; </li><li> если $$$|b| &gt; 0$$$, удалить последний символ строки $$$b$$$, то есть заменить $$$b$$$ на $$$b_1 b_2 \ldots b_{n-1}$$$. </li></ul><p>Заметьте, что после каждой из операций строка $$$a$$$ или $$$b$$$ могут стать пустыми.</p><p>Например, если $$$a=$$$<span class="tex-font-style-tt">«hello»</span> и $$$b=$$$<span class="tex-font-style-tt">«icpc»</span>, то вы можете применить следующую последовательность операций: </p><ul> <li> удалить первый символ строки $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ello»</span> и $$$b=$$$<span class="tex-font-style-tt">«icpc»</span>; </li><li> удалить первый символ строки $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ello»</span> и $$$b=$$$<span class="tex-font-style-tt">«cpc»</span>; </li><li> удалить первый символ строки $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ello»</span> и $$$b=$$$<span class="tex-font-style-tt">«pc»</span>; </li><li> удалить последний символ строки $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ell»</span> и $$$b=$$$<span class="tex-font-style-tt">«pc»</span>; </li><li> удалить последний символ строки $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ell»</span> и $$$b=$$$<span class="tex-font-style-tt">«p»</span>. </li></ul><p>По заданным строкам $$$a$$$ и $$$b$$$ найдите минимальное количество операций, за которые можно сделать строки $$$a$$$ и $$$b$$$ равными. Обратите внимание, что пустые строки также являются равными.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит строку $$$a$$$ ($$$1 \le |a| \le 20$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого набора входных данных содержит строку $$$b$$$ ($$$1 \le |b| \le 20$$$), состоящую из строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно число — минимальное количество операций, за которые можно сделать строки $$$a$$$ и $$$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 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 13 3 20 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="aabf449ea76131ca202795b8f15db2b3"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='aabf449ea76131ca202795b8f15db2b3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='aabf449ea76131ca202795b8f15db2b3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='aabf449ea76131ca202795b8f15db2b3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='aabf449ea76131ca202795b8f15db2b3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935561"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='aabf449ea76131ca202795b8f15db2b3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935561"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6b090310009f0539abd3483ec48320de8940741e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Двусторонние строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы строки $$$a$$$ и $$$b$$$, состоящие из строчных букв латинского алфавита. Вы можете сделать произвольное число следующих операций в произвольном порядке: </p><ul> <li> если $$$|a| &gt; 0$$$ (длина строки $$$a$$$ больше нуля), удалить первый символ строки $$$a$$$, то есть заменить $$$a$$$ на $$$a_2 a_3 \ldots a_n$$$; </li><li> если $$$|a| &gt; 0$$$, удалить последний символ строки $$$a$$$, то есть заменить $$$a$$$ на $$$a_1 a_2 \ldots a_{n-1}$$$; </li><li> если $$$|b| &gt; 0$$$ (длина строки $$$b$$$ больше нуля), удалить первый символ строки $$$b$$$, то есть заменить $$$b$$$ на $$$b_2 b_3 \ldots b_n$$$; </li><li> если $$$|b| &gt; 0$$$, удалить последний символ строки $$$b$$$, то есть заменить $$$b$$$ на $$$b_1 b_2 \ldots b_{n-1}$$$. </li></ul><p>Заметьте, что после каждой из операций строка $$$a$$$ или $$$b$$$ могут стать пустыми.</p><p>Например, если $$$a=$$$<span class="tex-font-style-tt">«hello»</span> и $$$b=$$$<span class="tex-font-style-tt">«icpc»</span>, то вы можете применить следующую последовательность операций: </p><ul> <li> удалить первый символ строки $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ello»</span> и $$$b=$$$<span class="tex-font-style-tt">«icpc»</span>; </li><li> удалить первый символ строки $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ello»</span> и $$$b=$$$<span class="tex-font-style-tt">«cpc»</span>; </li><li> удалить первый символ строки $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ello»</span> и $$$b=$$$<span class="tex-font-style-tt">«pc»</span>; </li><li> удалить последний символ строки $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ell»</span> и $$$b=$$$<span class="tex-font-style-tt">«pc»</span>; </li><li> удалить последний символ строки $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$<span class="tex-font-style-tt">«ell»</span> и $$$b=$$$<span class="tex-font-style-tt">«p»</span>. </li></ul><p>По заданным строкам $$$a$$$ и $$$b$$$ найдите минимальное количество операций, за которые можно сделать строки $$$a$$$ и $$$b$$$ равными. Обратите внимание, что пустые строки также являются равными.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит строку $$$a$$$ ($$$1 \le |a| \le 20$$$), состоящую из строчных букв латинского алфавита.</p><p>Вторая строка каждого набора входных данных содержит строку $$$b$$$ ($$$1 \le |b| \le 20$$$), состоящую из строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно число — минимальное количество операций, за которые можно сделать строки $$$a$$$ и $$$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 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 13 3 20 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:23</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf5b1805164e',t:'MTY5NjY2NzA2My42MzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1000"]
1506D
1506
D
ru
D. Эпическая трансформация
<div class="problem-statement"><div class="header"><div class="title">D. Эпическая трансформация</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a$$$ длины $$$n$$$, состоящий из целых чисел. Вы можете применять следующую операцию, состоящую из нескольких шагов, над массивом $$$a$$$ <span class="tex-font-style-bf">ноль</span> или более раз: </p><ul> <li> вы выбираете два <span class="tex-font-style-bf">различных</span> числа в массиве $$$a_i$$$ и $$$a_j$$$; </li><li> вы удаляете $$$i$$$-й и $$$j$$$-й элементы из массива. </li></ul><p>Например, если $$$n=6$$$ и $$$a=[1, 6, 1, 1, 4, 4]$$$, то вы можете произвести следующую последовательность операций: </p><ul> <li> выбираем $$$i=1, j=5$$$. Массив $$$a$$$ становится равным $$$[6, 1, 1, 4]$$$; </li><li> выбираем $$$i=1, j=2$$$. Массив $$$a$$$ становится равным $$$[1, 4]$$$. </li></ul><p>Каким может быть минимальный размер массива после применения к нему некоторой последовательности операций?</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$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальный возможный размер массива после применения к нему некоторой последовательности операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 1 6 1 1 4 4 2 1 2 2 1 1 5 4 5 4 5 4 6 2 3 2 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 2 1 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="4399b368b596f9f0300d4c517a5685ef"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='4399b368b596f9f0300d4c517a5685ef'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='4399b368b596f9f0300d4c517a5685ef'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='4399b368b596f9f0300d4c517a5685ef'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='4399b368b596f9f0300d4c517a5685ef'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935562"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4399b368b596f9f0300d4c517a5685ef'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935562"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_66312741687212f3f17a79702859d5be96c3cc40"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Эпическая трансформация</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a$$$ длины $$$n$$$, состоящий из целых чисел. Вы можете применять следующую операцию, состоящую из нескольких шагов, над массивом $$$a$$$ <span class="tex-font-style-bf">ноль</span> или более раз: </p><ul> <li> вы выбираете два <span class="tex-font-style-bf">различных</span> числа в массиве $$$a_i$$$ и $$$a_j$$$; </li><li> вы удаляете $$$i$$$-й и $$$j$$$-й элементы из массива. </li></ul><p>Например, если $$$n=6$$$ и $$$a=[1, 6, 1, 1, 4, 4]$$$, то вы можете произвести следующую последовательность операций: </p><ul> <li> выбираем $$$i=1, j=5$$$. Массив $$$a$$$ становится равным $$$[6, 1, 1, 4]$$$; </li><li> выбираем $$$i=1, j=2$$$. Массив $$$a$$$ становится равным $$$[1, 4]$$$. </li></ul><p>Каким может быть минимальный размер массива после применения к нему некоторой последовательности операций?</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$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальный возможный размер массива после применения к нему некоторой последовательности операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 1 6 1 1 4 4 2 1 2 2 1 1 5 4 5 4 5 4 6 2 3 2 1 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 2 1 0 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:24</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf63784b9d99',t:'MTY5NjY2NzA2NC45MzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1400"]
1506E
1506
E
ru
E. Восстановление перестановки
<div class="problem-statement"><div class="header"><div class="title">E. Восстановление перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановка — это последовательность из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$, в которой все числа встречаются ровно по одному разу. Например, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — перестановки, а $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — нет. </p><p>Поликарпу подарили перестановку $$$p$$$ чисел от $$$1$$$ до $$$n$$$. Однако, когда Поликарп пришёл домой, он заметил, что в кармане перестановка $$$p$$$ превратилась в массив $$$q$$$ согласно следующему правилу: </p><ul> <li> $$$q_i = \max(p_1, p_2, \ldots, p_i)$$$. </li></ul><p>Теперь Поликарпу стало интересно: какую лексикографически минимальную и лексикографически максимальную перестановки ему могли подарить.</p><p>Массив $$$a$$$ длины $$$n$$$ лексикографически меньше массива $$$b$$$ длины $$$n$$$, если существует индекс $$$i$$$ ($$$1 \le i \le n$$$), такой что первые $$$i-1$$$ элементов у массивов $$$a$$$ и $$$b$$$ совпадают, а $$$i$$$-й элемент у массива $$$a$$$ меньше, чем $$$i$$$-й элемент у массива $$$b$$$. Например массив $$$a=[1, 3, 2, 3]$$$ лексикографически меньше массива $$$b=[1, 3, 4, 2]$$$.</p><p>Например, если $$$n=7$$$ и $$$p=[3, 2, 4, 1, 7, 5, 6]$$$, тогда $$$q=[3, 3, 4, 4, 7, 7, 7]$$$ и следующие перестановки могли быть в качестве $$$p$$$ изначально: </p><ul> <li> $$$[3, 1, 4, 2, 7, 5, 6]$$$ (лексикографически минимальная перестановка); </li><li> $$$[3, 1, 4, 2, 7, 6, 5]$$$; </li><li> $$$[3, 2, 4, 1, 7, 5, 6]$$$; </li><li> $$$[3, 2, 4, 1, 7, 6, 5]$$$ (лексикографически максимальная перестановка). </li></ul><p>Для заданного массива $$$q$$$ найдите лексикографически минимальную и лексикографически максимальную перестановки, которые могли быть подарены Поликарпу изначально.</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$$$).</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$q_1, q_2, \ldots, q_n$$$ ($$$1 \le q_i \le n$$$).</p><p>Гарантируется, что массив $$$q$$$ был получен применением правила из условия к какой-то перестановке $$$p$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки: </p><ul> <li> в первой строке выведите $$$n$$$ целых чисел — лексикографически <span class="tex-font-style-bf">минимальную</span> перестановку, которая могла быть подарена Поликарпу изначально; </li><li> во второй строке выведите $$$n$$$ целых чисел — лексикографически <span class="tex-font-style-bf">максимальную</span> перестановку, которая могла быть подарена Поликарпу изначально. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 7 3 3 4 4 7 7 7 4 1 2 3 4 7 3 4 5 5 5 7 7 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 4 2 7 5 6 3 2 4 1 7 6 5 1 2 3 4 1 2 3 4 3 4 5 1 2 7 6 3 4 5 2 1 7 6 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="13ec12a5bcbf818db44807f9bab87edf"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='13ec12a5bcbf818db44807f9bab87edf'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='13ec12a5bcbf818db44807f9bab87edf'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='13ec12a5bcbf818db44807f9bab87edf'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='13ec12a5bcbf818db44807f9bab87edf'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935563"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='13ec12a5bcbf818db44807f9bab87edf'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935563"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_184792af3e48738a3a1f4f0974c1c168d79fa418"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Восстановление перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановка — это последовательность из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$, в которой все числа встречаются ровно по одному разу. Например, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — перестановки, а $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — нет. </p><p>Поликарпу подарили перестановку $$$p$$$ чисел от $$$1$$$ до $$$n$$$. Однако, когда Поликарп пришёл домой, он заметил, что в кармане перестановка $$$p$$$ превратилась в массив $$$q$$$ согласно следующему правилу: </p><ul> <li> $$$q_i = \max(p_1, p_2, \ldots, p_i)$$$. </li></ul><p>Теперь Поликарпу стало интересно: какую лексикографически минимальную и лексикографически максимальную перестановки ему могли подарить.</p><p>Массив $$$a$$$ длины $$$n$$$ лексикографически меньше массива $$$b$$$ длины $$$n$$$, если существует индекс $$$i$$$ ($$$1 \le i \le n$$$), такой что первые $$$i-1$$$ элементов у массивов $$$a$$$ и $$$b$$$ совпадают, а $$$i$$$-й элемент у массива $$$a$$$ меньше, чем $$$i$$$-й элемент у массива $$$b$$$. Например массив $$$a=[1, 3, 2, 3]$$$ лексикографически меньше массива $$$b=[1, 3, 4, 2]$$$.</p><p>Например, если $$$n=7$$$ и $$$p=[3, 2, 4, 1, 7, 5, 6]$$$, тогда $$$q=[3, 3, 4, 4, 7, 7, 7]$$$ и следующие перестановки могли быть в качестве $$$p$$$ изначально: </p><ul> <li> $$$[3, 1, 4, 2, 7, 5, 6]$$$ (лексикографически минимальная перестановка); </li><li> $$$[3, 1, 4, 2, 7, 6, 5]$$$; </li><li> $$$[3, 2, 4, 1, 7, 5, 6]$$$; </li><li> $$$[3, 2, 4, 1, 7, 6, 5]$$$ (лексикографически максимальная перестановка). </li></ul><p>Для заданного массива $$$q$$$ найдите лексикографически минимальную и лексикографически максимальную перестановки, которые могли быть подарены Поликарпу изначально.</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$$$).</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$q_1, q_2, \ldots, q_n$$$ ($$$1 \le q_i \le n$$$).</p><p>Гарантируется, что массив $$$q$$$ был получен применением правила из условия к какой-то перестановке $$$p$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки: </p><ul> <li> в первой строке выведите $$$n$$$ целых чисел — лексикографически <span class="tex-font-style-bf">минимальную</span> перестановку, которая могла быть подарена Поликарпу изначально; </li><li> во второй строке выведите $$$n$$$ целых чисел — лексикографически <span class="tex-font-style-bf">максимальную</span> перестановку, которая могла быть подарена Поликарпу изначально. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 7 3 3 4 4 7 7 7 4 1 2 3 4 7 3 4 5 5 5 7 7 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 4 2 7 5 6 3 2 4 1 7 6 5 1 2 3 4 1 2 3 4 3 4 5 1 2 7 6 3 4 5 2 1 7 6 1 1 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:26</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf6b7e543a5f',t:'MTY5NjY2NzA2Ni4yOTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1500"]
1506F
1506
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>Рассмотрим бесконечный треугольник, состоящий из слоев. Занумеруем слои, начиная с единицы, от верхней точки треугольника (сверху вниз). На $$$k$$$-м слое треугольника расположены $$$k$$$ точек, пронумерованных слева направо. Каждая точка бесконечного треугольника описывается парой чисел $$$(r, c)$$$ ($$$1 \le c \le r$$$), где $$$r$$$ — номер слоя, а $$$c$$$ — номер точки в слое. Из каждой точки $$$(r, c)$$$ исходит два <span class="tex-font-style-bf">направленных</span> ребра в точки $$$(r+1, c)$$$ и $$$(r+1, c+1)$$$, но только одно из рёбер активировано. Если $$$r + c$$$ — чётно, тогда активировано ребро в точку $$$(r+1, c)$$$, иначе активировано ребро в точку $$$(r+1, c+1)$$$. Изучите картинку для лучшего понимания.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1e03b2417de2a47038c84ffb48e68beb31a22907.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Черным цветом обозначены активированные ребра. Серым цветом обозначены не активированные ребра.</span> </center><p>Из точки $$$(r_1, c_1)$$$ можно дойти до точки $$$(r_2, c_2)$$$, если между ними существует путь только из <span class="tex-font-style-bf">активированных</span> рёбер. Например, на картинке выше существует путь из точки $$$(1, 1)$$$ в точку $$$(3, 2)$$$, но не существует пути из точки $$$(2, 1)$$$ в точку $$$(1, 1)$$$.</p><p>Изначально вы находитесь в точке $$$(1, 1)$$$. За каждый ход вы можете: </p><ul> <li> Заменить активированное ребро для точки $$$(r, c)$$$. То есть, если активировано ребро в точку $$$(r+1, c)$$$, то <span class="tex-font-style-bf">вместо него</span> активированным станет ребро в точку $$$(r+1, c+1)$$$, иначе, если активировано ребро в точку $$$(r+1, c+1)$$$, то <span class="tex-font-style-bf">вместо него</span> активированным станет ребро в точку $$$(r+1, c)$$$. Это действие увеличивает стоимость пути на $$$1$$$; </li><li> Переместиться из текущей точку в другую, перейдя по активированному ребру. Это действие <span class="tex-font-style-bf">не увеличивает</span> стоимость пути. </li></ul> <p>Вам дана последовательность из $$$n$$$ точек бесконечного треугольника $$$(r_1, c_1), (r_2, c_2), \ldots, (r_n, c_n)$$$. Найдите путь минимальной стоимости из точки $$$(1, 1)$$$, проходящий через все $$$n$$$ точек в <span class="tex-font-style-bf">произвольном</span> порядке.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор начинается со строки, в которой записано одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество точек, которые необходимо посетить.</p><p>Во второй строке находится $$$n$$$ чисел $$$r_1, r_2, \ldots, r_n$$$ ($$$1 \le r_i \le 10^9$$$), где $$$r_i$$$ — номер слоя, в котором находится $$$i$$$-я точка.</p><p>Во третьей строке находится $$$n$$$ чисел $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le r_i$$$), где $$$c_i$$$ — номер $$$i$$$-й точки в слое $$$r_i$$$.</p><p>Гарантируется, что все $$$n$$$ точек различны.</p><p>Гарантируется, что всегда существует хотя бы один способ обойти все $$$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> 4 3 1 4 2 1 3 1 2 2 4 2 3 2 1 1000000000 1 1000000000 4 3 10 5 8 2 5 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 999999999 2 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="6174d4155f6c8a3c693f515ff235f94b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6174d4155f6c8a3c693f515ff235f94b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='6174d4155f6c8a3c693f515ff235f94b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='6174d4155f6c8a3c693f515ff235f94b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах"> кратчайшие пути </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='6174d4155f6c8a3c693f515ff235f94b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935564"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6174d4155f6c8a3c693f515ff235f94b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935564"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7c0ffa271a7baaf6a4f70caa60323a9ff64120d3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Рассмотрим бесконечный треугольник, состоящий из слоев. Занумеруем слои, начиная с единицы, от верхней точки треугольника (сверху вниз). На $$$k$$$-м слое треугольника расположены $$$k$$$ точек, пронумерованных слева направо. Каждая точка бесконечного треугольника описывается парой чисел $$$(r, c)$$$ ($$$1 \le c \le r$$$), где $$$r$$$ — номер слоя, а $$$c$$$ — номер точки в слое. Из каждой точки $$$(r, c)$$$ исходит два <span class="tex-font-style-bf">направленных</span> ребра в точки $$$(r+1, c)$$$ и $$$(r+1, c+1)$$$, но только одно из рёбер активировано. Если $$$r + c$$$ — чётно, тогда активировано ребро в точку $$$(r+1, c)$$$, иначе активировано ребро в точку $$$(r+1, c+1)$$$. Изучите картинку для лучшего понимания.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1e03b2417de2a47038c84ffb48e68beb31a22907.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Черным цветом обозначены активированные ребра. Серым цветом обозначены не активированные ребра.</span> </center><p>Из точки $$$(r_1, c_1)$$$ можно дойти до точки $$$(r_2, c_2)$$$, если между ними существует путь только из <span class="tex-font-style-bf">активированных</span> рёбер. Например, на картинке выше существует путь из точки $$$(1, 1)$$$ в точку $$$(3, 2)$$$, но не существует пути из точки $$$(2, 1)$$$ в точку $$$(1, 1)$$$.</p><p>Изначально вы находитесь в точке $$$(1, 1)$$$. За каждый ход вы можете: </p><ul> <li> Заменить активированное ребро для точки $$$(r, c)$$$. То есть, если активировано ребро в точку $$$(r+1, c)$$$, то <span class="tex-font-style-bf">вместо него</span> активированным станет ребро в точку $$$(r+1, c+1)$$$, иначе, если активировано ребро в точку $$$(r+1, c+1)$$$, то <span class="tex-font-style-bf">вместо него</span> активированным станет ребро в точку $$$(r+1, c)$$$. Это действие увеличивает стоимость пути на $$$1$$$; </li><li> Переместиться из текущей точку в другую, перейдя по активированному ребру. Это действие <span class="tex-font-style-bf">не увеличивает</span> стоимость пути. </li></ul> <p>Вам дана последовательность из $$$n$$$ точек бесконечного треугольника $$$(r_1, c_1), (r_2, c_2), \ldots, (r_n, c_n)$$$. Найдите путь минимальной стоимости из точки $$$(1, 1)$$$, проходящий через все $$$n$$$ точек в <span class="tex-font-style-bf">произвольном</span> порядке.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор начинается со строки, в которой записано одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество точек, которые необходимо посетить.</p><p>Во второй строке находится $$$n$$$ чисел $$$r_1, r_2, \ldots, r_n$$$ ($$$1 \le r_i \le 10^9$$$), где $$$r_i$$$ — номер слоя, в котором находится $$$i$$$-я точка.</p><p>Во третьей строке находится $$$n$$$ чисел $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le r_i$$$), где $$$c_i$$$ — номер $$$i$$$-й точки в слое $$$r_i$$$.</p><p>Гарантируется, что все $$$n$$$ точек различны.</p><p>Гарантируется, что всегда существует хотя бы один способ обойти все $$$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> 4 3 1 4 2 1 3 1 2 2 4 2 3 2 1 1000000000 1 1000000000 4 3 10 5 8 2 5 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 999999999 2 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:27</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf73ee919d87',t:'MTY5NjY2NzA2Ny43NTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\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"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2000"]
1506G
1506
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.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>Вам задана строка $$$s$$$, состоящая из строчных букв латинского алфавита. Пока в строке $$$s$$$ есть <span class="tex-font-style-bf">хотя бы один символ, повторяющийся хотя бы дважды,</span> вы выполняете следующую операцию: </p><ul> <li> вы выбираете индекс $$$i$$$ ($$$1 \le i \le |s|$$$), такой что символ на позиции $$$i$$$ встречается <span class="tex-font-style-bf">хотя бы два</span> раза в строке $$$s$$$, и удаляете символ на позиции $$$i$$$, то есть заменяете $$$s$$$ на $$$s_1 s_2 \ldots s_{i-1} s_{i+1} s_{i+2} \ldots s_n$$$. </li></ul><p>Например, если $$$s=$$$<span class="tex-font-style-tt">«codeforces»</span>, то вы можете применить следующую последовательность операций: </p><ul> <li> $$$i=6 \Rightarrow s=$$$<span class="tex-font-style-tt">«codefrces»</span>; </li><li> $$$i=1 \Rightarrow s=$$$<span class="tex-font-style-tt">«odefrces»</span>; </li><li> $$$i=7 \Rightarrow s=$$$<span class="tex-font-style-tt">«odefrcs»</span>; </li></ul><p>По заданной строке $$$s$$$ найдите лексикографически максимальную строку, которая может быть получена после применения некоторой последовательности операций, оставляющей в строке <span class="tex-font-style-bf">только уникальные</span> символы.</p><p>Строка $$$a$$$ длины $$$n$$$ лексикографически меньше строки $$$b$$$ длины $$$m$$$, если: </p><ul> <li> существует индекс $$$i$$$ ($$$1 \le i \le \min(n, m)$$$), такой что первые $$$i-1$$$ символов у строк $$$a$$$ и $$$b$$$ совпадают, а $$$i$$$-й символ строки $$$a$$$ меньше, чем $$$i$$$-й символ строки $$$b$$$; </li><li> <span class="tex-font-style-bf">или</span> первые $$$\min(n, m)$$$ символов у строк $$$a$$$ и $$$b$$$ совпадают и $$$n &lt; m$$$. </li></ul><p>Например строка $$$a=$$$<span class="tex-font-style-tt">«aezakmi»</span> лексикографически меньше строки $$$b=$$$<span class="tex-font-style-tt">«aezus»</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следую $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных характеризуется строкой $$$s$$$, состоящей из строчных букв латинского алфавита ($$$1 \le |s| \le 2 \cdot 10^5$$$).</p><p>Гарантируется, что сумма длин строк во всех наборах входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите лексикографически максимальную строку, которая может быть получена после применения некоторой последовательности операций, оставляющей в строке <span class="tex-font-style-bf">только уникальные</span> символы.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 codeforces aezakmi abacaba convexhull swflldjgpaxs myneeocktxpqjpz </pre></div><div class="output"><div class="title">Выходные данные</div><pre> odfrces ezakmi cba convexhul wfldjgpaxs myneocktxqjpz </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="97165c3191d0bd8c51200171a1ed0bf3"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="d8001fc209707661823924fc04c06fc2df21b2de"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='97165c3191d0bd8c51200171a1ed0bf3'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1506%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='97165c3191d0bd8c51200171a1ed0bf3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1506">Codeforces Round 710 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='97165c3191d0bd8c51200171a1ed0bf3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1506/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='97165c3191d0bd8c51200171a1ed0bf3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="935565"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='97165c3191d0bd8c51200171a1ed0bf3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="935565"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/88986" title="Codeforces Round #710 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13351:13352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89007" title="Разбор" target="_blank">Разбор</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13363:13364" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1506">Задачи</a></li> <li><a href="/contest/1506/submit">Отослать</a></li> <li><a href="/contest/1506/my">Мои посылки</a></li> <li><a href="/contest/1506/status">Статус</a></li> <li><a href="/contest/1506/hacks">Взломы</a></li> <li><a href="/contest/1506/standings">Положение</a></li> <li><a href="/contest/1506/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e15f5f59915f644f4c29f22b9a608c3524152a7d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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.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>Вам задана строка $$$s$$$, состоящая из строчных букв латинского алфавита. Пока в строке $$$s$$$ есть <span class="tex-font-style-bf">хотя бы один символ, повторяющийся хотя бы дважды,</span> вы выполняете следующую операцию: </p><ul> <li> вы выбираете индекс $$$i$$$ ($$$1 \le i \le |s|$$$), такой что символ на позиции $$$i$$$ встречается <span class="tex-font-style-bf">хотя бы два</span> раза в строке $$$s$$$, и удаляете символ на позиции $$$i$$$, то есть заменяете $$$s$$$ на $$$s_1 s_2 \ldots s_{i-1} s_{i+1} s_{i+2} \ldots s_n$$$. </li></ul><p>Например, если $$$s=$$$<span class="tex-font-style-tt">«codeforces»</span>, то вы можете применить следующую последовательность операций: </p><ul> <li> $$$i=6 \Rightarrow s=$$$<span class="tex-font-style-tt">«codefrces»</span>; </li><li> $$$i=1 \Rightarrow s=$$$<span class="tex-font-style-tt">«odefrces»</span>; </li><li> $$$i=7 \Rightarrow s=$$$<span class="tex-font-style-tt">«odefrcs»</span>; </li></ul><p>По заданной строке $$$s$$$ найдите лексикографически максимальную строку, которая может быть получена после применения некоторой последовательности операций, оставляющей в строке <span class="tex-font-style-bf">только уникальные</span> символы.</p><p>Строка $$$a$$$ длины $$$n$$$ лексикографически меньше строки $$$b$$$ длины $$$m$$$, если: </p><ul> <li> существует индекс $$$i$$$ ($$$1 \le i \le \min(n, m)$$$), такой что первые $$$i-1$$$ символов у строк $$$a$$$ и $$$b$$$ совпадают, а $$$i$$$-й символ строки $$$a$$$ меньше, чем $$$i$$$-й символ строки $$$b$$$; </li><li> <span class="tex-font-style-bf">или</span> первые $$$\min(n, m)$$$ символов у строк $$$a$$$ и $$$b$$$ совпадают и $$$n &lt; m$$$. </li></ul><p>Например строка $$$a=$$$<span class="tex-font-style-tt">«aezakmi»</span> лексикографически меньше строки $$$b=$$$<span class="tex-font-style-tt">«aezus»</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следую $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных характеризуется строкой $$$s$$$, состоящей из строчных букв латинского алфавита ($$$1 \le |s| \le 2 \cdot 10^5$$$).</p><p>Гарантируется, что сумма длин строк во всех наборах входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите лексикографически максимальную строку, которая может быть получена после применения некоторой последовательности операций, оставляющей в строке <span class="tex-font-style-bf">только уникальные</span> символы.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 codeforces aezakmi abacaba convexhull swflldjgpaxs myneeocktxpqjpz </pre></div><div class="output"><div class="title">Выходные данные</div><pre> odfrces ezakmi cba convexhul wfldjgpaxs myneocktxqjpz </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:29</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf7d3de97a7d',t:'MTY5NjY2NzA2OS4wOTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2000"]
1508A
1508
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-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Koyomi Kanou усердно работает над своей мечтой стать писательницей. Чтобы попрактиковаться, она решила принять участие в <span class="tex-font-style-it">Конкурсе по Написанию Бинарных Романов</span>. Указание к конкурсу состоит из трёх бинарных строк длины $$$2n$$$. Корректным романом для конкурса является бинарная строка длины не более $$$3n$$$, содержащая в качестве подпоследовательностей <span class="tex-font-style-bf">не менее двух</span> из трёх данных строк.</p><p>Koyomi только что получила три строки — указание от организаторов конкурса. Помогите ей написать корректный роман для конкурса.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$, удалив несколько (возможно, ноль) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>Каждая из следующих трех строк содержит бинарную строку длины $$$2n$$$. Гарантируется, что эти три строки попарно различны.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую бинарную строку длины не более $$$3n$$$, которая в качестве подпоследовательностей содержит как минимум две из заданных бинарных строк.</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 1 00 11 01 3 011001 111010 010001 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 010 011001010 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных бинарные строки <span class="tex-font-style-tt">00</span> и <span class="tex-font-style-tt">01</span> являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">0</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">01</span>0</span>. Обратите внимание, что <span class="tex-font-style-tt">11</span> не является подпоследовательностью выходной строки, но это не требуется.</p><p>Во втором наборе входных данных все три входных строки являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011</span>0<span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">01</span>0</span>, <span class="tex-font-style-tt">0<span class="tex-font-style-bf">11</span>00<span class="tex-font-style-bf">1010</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">100</span>1<span class="tex-font-style-bf">01</span>0</span>.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="092fd0e772f3e32b6cf0e962aa6c278f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4c1538dfd9494076dc1e10302daf27669dc2adff"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='092fd0e772f3e32b6cf0e962aa6c278f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1508%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='092fd0e772f3e32b6cf0e962aa6c278f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1508">Codeforces Round 715 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='092fd0e772f3e32b6cf0e962aa6c278f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1508/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1900 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='092fd0e772f3e32b6cf0e962aa6c278f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958781"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='092fd0e772f3e32b6cf0e962aa6c278f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958781"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13506" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13520" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1508">Задачи</a></li> <li><a href="/contest/1508/submit">Отослать</a></li> <li><a href="/contest/1508/my">Мои посылки</a></li> <li><a href="/contest/1508/status">Статус</a></li> <li><a href="/contest/1508/hacks">Взломы</a></li> <li><a href="/contest/1508/room/1">Комната</a></li> <li><a href="/contest/1508/standings">Положение</a></li> <li><a href="/contest/1508/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_53cc9131e8ec1c78f6b6bb589baeca569f07bb13"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Koyomi Kanou усердно работает над своей мечтой стать писательницей. Чтобы попрактиковаться, она решила принять участие в <span class="tex-font-style-it">Конкурсе по Написанию Бинарных Романов</span>. Указание к конкурсу состоит из трёх бинарных строк длины $$$2n$$$. Корректным романом для конкурса является бинарная строка длины не более $$$3n$$$, содержащая в качестве подпоследовательностей <span class="tex-font-style-bf">не менее двух</span> из трёх данных строк.</p><p>Koyomi только что получила три строки — указание от организаторов конкурса. Помогите ей написать корректный роман для конкурса.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$, удалив несколько (возможно, ноль) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>Каждая из следующих трех строк содержит бинарную строку длины $$$2n$$$. Гарантируется, что эти три строки попарно различны.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую бинарную строку длины не более $$$3n$$$, которая в качестве подпоследовательностей содержит как минимум две из заданных бинарных строк.</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 1 00 11 01 3 011001 111010 010001 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 010 011001010 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных бинарные строки <span class="tex-font-style-tt">00</span> и <span class="tex-font-style-tt">01</span> являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">0</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">01</span>0</span>. Обратите внимание, что <span class="tex-font-style-tt">11</span> не является подпоследовательностью выходной строки, но это не требуется.</p><p>Во втором наборе входных данных все три входных строки являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011</span>0<span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">01</span>0</span>, <span class="tex-font-style-tt">0<span class="tex-font-style-bf">11</span>00<span class="tex-font-style-bf">1010</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">100</span>1<span class="tex-font-style-bf">01</span>0</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:30</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf8598af9db4',t:'MTY5NjY2NzA3MC41NDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\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", "\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\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1900"]
1508B
1508
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>Seiji Maki не только любит наблюдать за развитием отношений, он также любит наблюдать за последовательностями чисел, особенно перестановками. Сегодня он смотрит на <span class="tex-font-style-it">почти отсортированные</span> перестановки.</p><p>Перестановка $$$a_1, a_2, \dots, a_n$$$ чисел $$$1, 2, \dots, n$$$ считается <span class="tex-font-style-it">почти отсортированной</span>, если условие $$$a_{i + 1} \ge a_i - 1$$$ выполняется для всех $$$i$$$ от $$$1$$$ до $$$n - 1$$$ включительно.</p><p>Maki рассматривает список всех почти отсортированных перестановок чисел $$$1, 2, \dots, n$$$, приведенных в лексикографическом порядке, и хочет найти в этом списке перестановку $$$k$$$-ю. Можете ли вы помочь ему найти такую перестановку?</p><p>Перестановка $$$p$$$ лексикографически меньше перестановки $$$q$$$, если и только если выполняется следующее:</p><ul><li> в первой позиции, где $$$p$$$ и $$$q$$$ различны, в перестановке $$$p$$$ элемент меньше, чем соответствующий элемент в $$$q$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки, содержащей два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le k \le 10^{18}$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую $$$k$$$-ю почти отсортированную перестановку длины $$$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> 5 1 1 1 2 3 3 6 5 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого и второго набора входных данных список почти отсортированных перестановок с $$$n = 1$$$ составляет $$$\{[1]\}$$$.</p><p>Для третьего и пятого набора входных данных список почти отсортированных перестановок с $$$n = 3$$$ составляет $$$\{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="5c49553f6bf0a474779f30cc681d80c7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4c1538dfd9494076dc1e10302daf27669dc2adff"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='5c49553f6bf0a474779f30cc681d80c7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1508%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='5c49553f6bf0a474779f30cc681d80c7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1508">Codeforces Round 715 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='5c49553f6bf0a474779f30cc681d80c7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1508/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='5c49553f6bf0a474779f30cc681d80c7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958782"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5c49553f6bf0a474779f30cc681d80c7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958782"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13506" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13520" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1508">Задачи</a></li> <li><a href="/contest/1508/submit">Отослать</a></li> <li><a href="/contest/1508/my">Мои посылки</a></li> <li><a href="/contest/1508/status">Статус</a></li> <li><a href="/contest/1508/hacks">Взломы</a></li> <li><a href="/contest/1508/room/1">Комната</a></li> <li><a href="/contest/1508/standings">Положение</a></li> <li><a href="/contest/1508/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1f4f50a15703e4968bef5735a6eabce2cbf476a4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Seiji Maki не только любит наблюдать за развитием отношений, он также любит наблюдать за последовательностями чисел, особенно перестановками. Сегодня он смотрит на <span class="tex-font-style-it">почти отсортированные</span> перестановки.</p><p>Перестановка $$$a_1, a_2, \dots, a_n$$$ чисел $$$1, 2, \dots, n$$$ считается <span class="tex-font-style-it">почти отсортированной</span>, если условие $$$a_{i + 1} \ge a_i - 1$$$ выполняется для всех $$$i$$$ от $$$1$$$ до $$$n - 1$$$ включительно.</p><p>Maki рассматривает список всех почти отсортированных перестановок чисел $$$1, 2, \dots, n$$$, приведенных в лексикографическом порядке, и хочет найти в этом списке перестановку $$$k$$$-ю. Можете ли вы помочь ему найти такую перестановку?</p><p>Перестановка $$$p$$$ лексикографически меньше перестановки $$$q$$$, если и только если выполняется следующее:</p><ul><li> в первой позиции, где $$$p$$$ и $$$q$$$ различны, в перестановке $$$p$$$ элемент меньше, чем соответствующий элемент в $$$q$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки, содержащей два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le k \le 10^{18}$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую $$$k$$$-ю почти отсортированную перестановку длины $$$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> 5 1 1 1 2 3 3 6 5 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого и второго набора входных данных список почти отсортированных перестановок с $$$n = 1$$$ составляет $$$\{[1]\}$$$.</p><p>Для третьего и пятого набора входных данных список почти отсортированных перестановок с $$$n = 3$$$ составляет $$$\{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:31</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf8eac141628',t:'MTY5NjY2NzA3MS44ODgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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", "\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", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1800"]
1508C
1508
C
ru
C. Завершите MST
<div class="problem-statement"><div class="header"><div class="title">C. Завершите MST</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>Как преподаватель, Riko Hakozaki часто помогает ученикам в решении задач по различным предметам. Сегодня ее попросили помочь с задачей по программированию, которая заключается в следующем.</p><p>Вам выдается неориентированный полный граф с $$$n$$$ вершинами, где для некоторых ребер заданы положительные веса, а для остальных нет. Вам нужно назначить всем еще не назначенным рёбрам <span class="tex-font-style-bf">неотрицательные веса</span> так, чтобы у получившегося графа <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">XOR (побитовое исключающее ИЛИ)</a> всех весов был равен $$$0$$$.</p><p>Определим <span class="tex-font-style-it">уродство</span> полного графа как вес его <a href="https://ru.wikipedia.org/wiki/Минимальное_остовное_дерево">минимального остовного дерева</a>, где вес остовного дерева равен сумме весов его рёбер. Нужно назначить веса так, чтобы уродство получившегося графа было как можно меньше.</p><p>Напомним, что неориентированный полный граф с $$$n$$$ вершинами содержит все рёбра $$$(u, v)$$$ с $$$1 \le u &lt; v \le n$$$; такой граф имеет $$$\frac{n(n-1)}{2}$$$ рёбер.</p><p>Она не знает, как решить эту задачу, поэтому просит вас решить ее за нее.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2} - 1)$$$)  — количество вершин и количество предварительно назначенных рёбер. Гарантируется, что есть по крайней мере одно неназначенное ребро.</p><p>$$$i$$$-я из следующих строк $$$m$$$ содержит три целых числа $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u \ne v$$$, $$$1 \le w_i &lt; 2^{30}$$$), обознаающие ребро от $$$u_i$$$ до $$$v_i$$$, которому был назначен вес $$$w_i$$$. Ни одно ребро не появляется во вводе более одного раза.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите в одной строке одно целое число  — минимальное уродство среди всех возможных назначений весов с XOR суммой равной $$$0$$$.</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 2 1 14 1 4 14 3 2 15 4 3 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a7a280c2f88b120ff0839966d25330c968719a1c.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="d7627e311f1b05b0a3aad21ac20b3a2b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4c1538dfd9494076dc1e10302daf27669dc2adff"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d7627e311f1b05b0a3aad21ac20b3a2b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1508%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='d7627e311f1b05b0a3aad21ac20b3a2b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1508">Codeforces Round 715 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='d7627e311f1b05b0a3aad21ac20b3a2b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1508/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='d7627e311f1b05b0a3aad21ac20b3a2b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958783"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d7627e311f1b05b0a3aad21ac20b3a2b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958783"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13506" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13520" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1508">Задачи</a></li> <li><a href="/contest/1508/submit">Отослать</a></li> <li><a href="/contest/1508/my">Мои посылки</a></li> <li><a href="/contest/1508/status">Статус</a></li> <li><a href="/contest/1508/hacks">Взломы</a></li> <li><a href="/contest/1508/room/1">Комната</a></li> <li><a href="/contest/1508/standings">Положение</a></li> <li><a href="/contest/1508/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4ae68bb85a45f70744c7f11e7770169278a80d81"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Завершите MST</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>Как преподаватель, Riko Hakozaki часто помогает ученикам в решении задач по различным предметам. Сегодня ее попросили помочь с задачей по программированию, которая заключается в следующем.</p><p>Вам выдается неориентированный полный граф с $$$n$$$ вершинами, где для некоторых ребер заданы положительные веса, а для остальных нет. Вам нужно назначить всем еще не назначенным рёбрам <span class="tex-font-style-bf">неотрицательные веса</span> так, чтобы у получившегося графа <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">XOR (побитовое исключающее ИЛИ)</a> всех весов был равен $$$0$$$.</p><p>Определим <span class="tex-font-style-it">уродство</span> полного графа как вес его <a href="https://ru.wikipedia.org/wiki/Минимальное_остовное_дерево">минимального остовного дерева</a>, где вес остовного дерева равен сумме весов его рёбер. Нужно назначить веса так, чтобы уродство получившегося графа было как можно меньше.</p><p>Напомним, что неориентированный полный граф с $$$n$$$ вершинами содержит все рёбра $$$(u, v)$$$ с $$$1 \le u &lt; v \le n$$$; такой граф имеет $$$\frac{n(n-1)}{2}$$$ рёбер.</p><p>Она не знает, как решить эту задачу, поэтому просит вас решить ее за нее.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2} - 1)$$$)  — количество вершин и количество предварительно назначенных рёбер. Гарантируется, что есть по крайней мере одно неназначенное ребро.</p><p>$$$i$$$-я из следующих строк $$$m$$$ содержит три целых числа $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u \ne v$$$, $$$1 \le w_i &lt; 2^{30}$$$), обознаающие ребро от $$$u_i$$$ до $$$v_i$$$, которому был назначен вес $$$w_i$$$. Ни одно ребро не появляется во вводе более одного раза.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите в одной строке одно целое число  — минимальное уродство среди всех возможных назначений весов с XOR суммой равной $$$0$$$.</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 2 1 14 1 4 14 3 2 15 4 3 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a7a280c2f88b120ff0839966d25330c968719a1c.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:33</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf96ff859d9e',t:'MTY5NjY2NzA3My4yMjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\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", "\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", "\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\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2500"]
1508D
1508
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">В связи со специфическим инцидентом на баскетбольной тренировке, Akari придумал следующую задачу со спортивного программирования!</span></p><p>Вам даны $$$n$$$ точек на плоскости, никакие три из которых не лежат на одной прямой. Изначально точка $$$i$$$ имеет метку $$$a_i$$$, причем метки $$$a_1, a_2, \dots, a_n$$$ образуют перестановку чисел $$$1, 2, \dots, n$$$.</p><p>Вы можете менять эти метки с помощью следующей операции: </p><ol> <li> Выберите два разных целых числа $$$i$$$ и $$$j$$$ между $$$1$$$ и $$$n$$$. </li><li> Поменяйте местами метки точек $$$i$$$ и $$$j$$$. </li><li> Нарисуйте отрезок между точками $$$i$$$ и $$$j$$$. </li></ol><p>Последовательность операций корректна, если после применения всех операций в последовательности точка $$$k$$$ имеет метку $$$k$$$ для всех $$$k$$$ от $$$1$$$ до $$$n$$$ включительно, и нарисованные отрезки не пересекаются внутри друг друга. Формально, если два отрезка пересекаются, то они должны сделать это в общей конечной точке обоих отрезков.</p><p>В частности, все нарисованные отрезки должны быть попарно различными.</p><p>Найдите любую корректную последовательность операций или определите, что ее нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$n$$$ ($$$3 \le n \le 2000$$$)  — количество точек.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится три целых числа $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ ($$$-10^6 \le x_i, y_i \le 10^6$$$, $$$1 \le a_i \le n$$$), что означает, что точка $$$i$$$ имеет координаты $$$(x_i, y_i)$$$ и изначально имеет метку $$$a_i$$$.</p><p>Гарантируется, что все точки различны, никакие три точки не лежат на одной прямой, а метки $$$a_1, a_2, \dots, a_n$$$ образуют перестановку чисел $$$1, 2, \dots, n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно выполнить корректную последовательность операций, выведите $$$-1$$$.</p><p>В противном случае выведите целое число $$$k$$$ ($$$0 \le k \le \frac{n(n - 1)}{2}$$$)  — количество выполняемых операций, а затем $$$k$$$ строк, каждая из которых содержит два целых числа $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$, $$$i\neq j$$$)  — номера точек, выбранных для операции.</p><p>Обратите внимание, что вам не требуется минимизировать или максимизировать значение $$$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> 5 -1 -2 2 3 0 5 1 3 4 4 -3 3 5 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 2 5 3 4 5 1 5 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 4 1 0 0 2 -3 -2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая анимация демонстрирует первый пример. Черные числа обозначают номера точек, а оранжевые — их метки.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/52799567d91ba17b218fab147b23e5a415955758.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><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="ab16a395a1035b7f7ea76bcfde5317b6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4c1538dfd9494076dc1e10302daf27669dc2adff"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ab16a395a1035b7f7ea76bcfde5317b6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1508%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='ab16a395a1035b7f7ea76bcfde5317b6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1508">Codeforces Round 715 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='ab16a395a1035b7f7ea76bcfde5317b6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1508/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Геометрия"> геометрия </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound 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='ab16a395a1035b7f7ea76bcfde5317b6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958784"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ab16a395a1035b7f7ea76bcfde5317b6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958784"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13506" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13520" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1508">Задачи</a></li> <li><a href="/contest/1508/submit">Отослать</a></li> <li><a href="/contest/1508/my">Мои посылки</a></li> <li><a href="/contest/1508/status">Статус</a></li> <li><a href="/contest/1508/hacks">Взломы</a></li> <li><a href="/contest/1508/room/1">Комната</a></li> <li><a href="/contest/1508/standings">Положение</a></li> <li><a href="/contest/1508/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0adcb34b0002c5d703700dc8b068b4a83b40d5f1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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">В связи со специфическим инцидентом на баскетбольной тренировке, Akari придумал следующую задачу со спортивного программирования!</span></p><p>Вам даны $$$n$$$ точек на плоскости, никакие три из которых не лежат на одной прямой. Изначально точка $$$i$$$ имеет метку $$$a_i$$$, причем метки $$$a_1, a_2, \dots, a_n$$$ образуют перестановку чисел $$$1, 2, \dots, n$$$.</p><p>Вы можете менять эти метки с помощью следующей операции: </p><ol> <li> Выберите два разных целых числа $$$i$$$ и $$$j$$$ между $$$1$$$ и $$$n$$$. </li><li> Поменяйте местами метки точек $$$i$$$ и $$$j$$$. </li><li> Нарисуйте отрезок между точками $$$i$$$ и $$$j$$$. </li></ol><p>Последовательность операций корректна, если после применения всех операций в последовательности точка $$$k$$$ имеет метку $$$k$$$ для всех $$$k$$$ от $$$1$$$ до $$$n$$$ включительно, и нарисованные отрезки не пересекаются внутри друг друга. Формально, если два отрезка пересекаются, то они должны сделать это в общей конечной точке обоих отрезков.</p><p>В частности, все нарисованные отрезки должны быть попарно различными.</p><p>Найдите любую корректную последовательность операций или определите, что ее нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$n$$$ ($$$3 \le n \le 2000$$$)  — количество точек.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится три целых числа $$$x_i$$$, $$$y_i$$$, $$$a_i$$$ ($$$-10^6 \le x_i, y_i \le 10^6$$$, $$$1 \le a_i \le n$$$), что означает, что точка $$$i$$$ имеет координаты $$$(x_i, y_i)$$$ и изначально имеет метку $$$a_i$$$.</p><p>Гарантируется, что все точки различны, никакие три точки не лежат на одной прямой, а метки $$$a_1, a_2, \dots, a_n$$$ образуют перестановку чисел $$$1, 2, \dots, n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно выполнить корректную последовательность операций, выведите $$$-1$$$.</p><p>В противном случае выведите целое число $$$k$$$ ($$$0 \le k \le \frac{n(n - 1)}{2}$$$)  — количество выполняемых операций, а затем $$$k$$$ строк, каждая из которых содержит два целых числа $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$, $$$i\neq j$$$)  — номера точек, выбранных для операции.</p><p>Обратите внимание, что вам не требуется минимизировать или максимизировать значение $$$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> 5 -1 -2 2 3 0 5 1 3 4 4 -3 3 5 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 1 2 5 3 4 5 1 5 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 4 1 0 0 2 -3 -2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая анимация демонстрирует первый пример. Черные числа обозначают номера точек, а оранжевые — их метки.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/52799567d91ba17b218fab147b23e5a415955758.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере все метки изначально находятся в правильном положении, поэтому никаких операций не требуется.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:34</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bf9f5c4f4971',t:'MTY5NjY2NzA3NC41OTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*3000"]
1508E
1508
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>Yuu Koito и Touko Nanami — молодожёны! В день свадьбы Yuu подарила Touko ориентированное дерево с $$$n$$$ вершинами и корнем в $$$1$$$, а также маркировку $$$a$$$, которая является <span class="tex-font-style-it">некоторым</span> DFS обходом дерева. Каждое ребро в этом дереве направлено в сторону от корня.</p><p>Следующий алгоритм после вызова <span class="tex-font-style-tt">dfs(1)</span> возвращает $$$a$$$ — DFS-обход дерева, корнем которого является $$$1$$$:</p><pre class="verbatim"><br/>номер := 0<br/>a := массив длины n<br/><br/>функция dfs(u):<br/> номер := номер + 1<br/> a[u] := номер<br/> для всех v, для которых есть ориентированное ребро (u -&gt; v):<br/> dfs(v)<br/></pre><p>Обратите внимание, что для дерева может существовать несколько различных DFS-обходов</p><p>Touko настолько понравился подарок, что она решила поиграть с ним! Каждый день, начиная с дня после свадьбы, Touko выполняет следующую процедуру один раз:</p><ul><li> Среди всех ориентированных рёбер $$$u \rightarrow v$$$ таких, что $$$a_u &lt; a_v$$$, выберите рёбро $$$u' \rightarrow v'$$$ с лексикографически минимальной парой $$$(a_{u'}, a_{v'})$$$. </li><li> Обменяйте местами $$$a_{u'}$$$ и $$$a_{v'}$$$.</li></ul><p>Прошли дни со свадьбы, а Touko как-то забыла, когда была свадьба, и какой была оригинальная маркировка $$$a$$$! Опасаясь, что Yuu может разозлиться, Touko решила попросить вас определить эту информацию, используя текущую маркировку.</p><p>Будучи ее хорошим другом, вы должны найти количество дней, прошедших со свадьбы, и оригинальную маркировку дерева. Однако есть шанс, что Touko могла ошибиться в процессе, в результате чего текущую маркировку невозможно получить ни из какой начальной маркировки, в этом случае, пожалуйста, сообщите об этом Touko.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится целое число $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — количество вершин в дереве.</p><p>Во второй строке содержатся $$$n$$$ целые числа $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, все $$$a_i$$$ различны) — текущая маркировка дерева.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), описывающие ориентированное ребро от $$$u_i$$$ до $$$v_i$$$. Ребра образуют корневое ориентированное дерево с корнем в $$$1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если текущую маркировку невозможно получить ни из какого DFS-обхода, выведите <span class="tex-font-style-tt">NO</span>.</p><p>В противном случае в первой строке выведите <span class="tex-font-style-tt">YES</span>. Во второй строке выведите единственное целое число, обозначающее количество дней со дня свадьбы. В третьей строке выведите $$$n$$$ чисел через пробел, обозначающих оригинальную маркировку дерева. </p><p>Если есть несколько правильных решений, вы можете вывести любое. Это означает, что вы можете вывести любую пару (DFS-обход, количество дней), для которой мы получим текущую конфигурацию, начав из DFS-обхода, который вы предоставили, ровно через предоставленное вами количество дней.</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 5 2 1 7 6 3 1 5 7 6 1 2 2 7 3 4 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 5 1 4 2 3 7 6 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 7 6 5 3 1 4 2 4 3 2 5 3 7 1 4 7 2 2 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая анимация демонстрирует первый пример. Белая метка внутри вершины обозначает номер вершины $$$i$$$, а оранжевая метка — значение $$$a_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d7bef343c63d66b4e06456e9d7062a9f69bcf396.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="63b3a6fa6febe87e9c364224f8f0d83f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4c1538dfd9494076dc1e10302daf27669dc2adff"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='63b3a6fa6febe87e9c364224f8f0d83f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1508%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='63b3a6fa6febe87e9c364224f8f0d83f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1508">Codeforces Round 715 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='63b3a6fa6febe87e9c364224f8f0d83f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1508/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='63b3a6fa6febe87e9c364224f8f0d83f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958785"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='63b3a6fa6febe87e9c364224f8f0d83f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958785"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13506" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13520" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1508">Задачи</a></li> <li><a href="/contest/1508/submit">Отослать</a></li> <li><a href="/contest/1508/my">Мои посылки</a></li> <li><a href="/contest/1508/status">Статус</a></li> <li><a href="/contest/1508/hacks">Взломы</a></li> <li><a href="/contest/1508/room/1">Комната</a></li> <li><a href="/contest/1508/standings">Положение</a></li> <li><a href="/contest/1508/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c25d518c65f535688b1410a429b09f0eb23c75c4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Yuu Koito и Touko Nanami — молодожёны! В день свадьбы Yuu подарила Touko ориентированное дерево с $$$n$$$ вершинами и корнем в $$$1$$$, а также маркировку $$$a$$$, которая является <span class="tex-font-style-it">некоторым</span> DFS обходом дерева. Каждое ребро в этом дереве направлено в сторону от корня.</p><p>Следующий алгоритм после вызова <span class="tex-font-style-tt">dfs(1)</span> возвращает $$$a$$$ — DFS-обход дерева, корнем которого является $$$1$$$:</p><pre class="verbatim"><br />номер := 0<br />a := массив длины n<br /><br />функция dfs(u):<br /> номер := номер + 1<br /> a[u] := номер<br /> для всех v, для которых есть ориентированное ребро (u -&gt; v):<br /> dfs(v)<br /></pre><p>Обратите внимание, что для дерева может существовать несколько различных DFS-обходов</p><p>Touko настолько понравился подарок, что она решила поиграть с ним! Каждый день, начиная с дня после свадьбы, Touko выполняет следующую процедуру один раз:</p><ul><li> Среди всех ориентированных рёбер $$$u \rightarrow v$$$ таких, что $$$a_u &lt; a_v$$$, выберите рёбро $$$u' \rightarrow v'$$$ с лексикографически минимальной парой $$$(a_{u'}, a_{v'})$$$. </li><li> Обменяйте местами $$$a_{u'}$$$ и $$$a_{v'}$$$.</li></ul><p>Прошли дни со свадьбы, а Touko как-то забыла, когда была свадьба, и какой была оригинальная маркировка $$$a$$$! Опасаясь, что Yuu может разозлиться, Touko решила попросить вас определить эту информацию, используя текущую маркировку.</p><p>Будучи ее хорошим другом, вы должны найти количество дней, прошедших со свадьбы, и оригинальную маркировку дерева. Однако есть шанс, что Touko могла ошибиться в процессе, в результате чего текущую маркировку невозможно получить ни из какой начальной маркировки, в этом случае, пожалуйста, сообщите об этом Touko.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится целое число $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — количество вершин в дереве.</p><p>Во второй строке содержатся $$$n$$$ целые числа $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, все $$$a_i$$$ различны) — текущая маркировка дерева.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), описывающие ориентированное ребро от $$$u_i$$$ до $$$v_i$$$. Ребра образуют корневое ориентированное дерево с корнем в $$$1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если текущую маркировку невозможно получить ни из какого DFS-обхода, выведите <span class="tex-font-style-tt">NO</span>.</p><p>В противном случае в первой строке выведите <span class="tex-font-style-tt">YES</span>. Во второй строке выведите единственное целое число, обозначающее количество дней со дня свадьбы. В третьей строке выведите $$$n$$$ чисел через пробел, обозначающих оригинальную маркировку дерева. </p><p>Если есть несколько правильных решений, вы можете вывести любое. Это означает, что вы можете вывести любую пару (DFS-обход, количество дней), для которой мы получим текущую конфигурацию, начав из DFS-обхода, который вы предоставили, ровно через предоставленное вами количество дней.</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 5 2 1 7 6 3 1 5 7 6 1 2 2 7 3 4 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES 5 1 4 2 3 7 6 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 7 6 5 3 1 4 2 4 3 2 5 3 7 1 4 7 2 2 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая анимация демонстрирует первый пример. Белая метка внутри вершины обозначает номер вершины $$$i$$$, а оранжевая метка — значение $$$a_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d7bef343c63d66b4e06456e9d7062a9f69bcf396.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:35</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfa81ea31610',t:'MTY5NjY2NzA3NS45ODgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\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", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3100"]
1508F
1508
F
ru
F. Оптимальное кодирование
<div class="problem-statement"><div class="header"><div class="title">F. Оптимальное кодирование</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>Любимая последовательность чисел Touko — это перестановка $$$a_1, a_2, \dots, a_n$$$ чисел $$$1, 2, \dots, n$$$, и она хочет коллекцию перестановок, похожих на ее любимую перестановку.</p><p>У нее есть коллекция $$$q$$$ отрезков вида $$$[l_i, r_i]$$$ с $$$1 \le l_i \le r_i \le n$$$. Для создания перестановок, похожих на ее любимую перестановку, она придумала следующее определение:</p><ul> <li> Перестановка $$$b_1, b_2, \dots, b_n$$$ позволяет интервалу $$$[l', r']$$$ <span class="tex-font-style-it">удерживать свою форму</span>, если для любой пары целых $$$(x, y)$$$ таких, что $$$l' \le x &lt; y \le r'$$$, неравенство $$$b_x &lt; b_y$$$ выполняется тогда и только тогда, когда $$$a_x &lt; a_y$$$. </li><li> Перестановка $$$b_1, b_2, \dots, b_n$$$ называется <span class="tex-font-style-it">$$$k$$$-похожей</span>, если $$$b$$$ позволяет всем интервалам $$$[l_i, r_i]$$$ для $$$1 \le i \le k$$$ сохранять свою форму. </li></ul><p>Yuu хочет найти все $$$k$$$-похожие перестановки для Touko, но это оказалось очень сложной задачей. Вместо этого Yuu будет <span class="tex-font-style-it">кодировать</span> набор всех $$$k$$$-похожих перестановок ориентированными ациклическими графами (DAG). Yuu также придумала для себя следующие определения:</p><ul> <li> Перестановка $$$b_1, b_2, \dots, b_n$$$ <span class="tex-font-style-it">удовлетворяет</span> DAG $$$G'$$$, если для всех ребер $$$u \to v$$$ в $$$G'$$$ выполняется $$$b_u &lt; b_v$$$. </li><li> <span class="tex-font-style-it">$$$k$$$-кодирование</span> — это DAG $$$G_k$$$ на наборе вершин $$$1, 2, \dots, n$$$ такой, что перестановка $$$b_1, b_2, \dots, b_n$$$ удовлетворяет $$$G_k$$$, если и только если $$$b$$$ является $$$k$$$-похожей. </li></ul><p>Поскольку Yuu сегодня свободна, она хочет выяснить минимальное количество ребер среди всех $$$k$$$-кодирований для каждого $$$k$$$ от $$$1$$$ до $$$q$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 25\,000$$$, $$$1 \le q \le 100\,000$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$, которые образуют перестановку $$$1, 2, \dots, n$$$.</p><p>В $$$i$$$-й из следующих строк $$$q$$$ содержатся два целых числа $$$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>Выведите $$$q$$$ строк. $$$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 2 4 1 3 1 3 2 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 4 3 7 4 8 1 5 2 6 3 6 1 6 3 8 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 5 9 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 10 10 5 1 2 7 3 9 4 6 8 2 2 4 5 6 8 4 10 4 4 2 7 2 2 7 8 3 7 2 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 3 6 6 9 9 9 9 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера:</p><ul><li> Все $$$1$$$-похожие перестановки должны позволять интервалу $$$[1, 3]$$$ удерживать свою форму. Поэтому набор всех $$$1$$$-похожих перестановок составляет $$$\{[3, 4, 2, 1], [3, 4, 1, 2], [2, 4, 1, 3], [2, 3, 1, 4]\}$$$. Оптимальным кодированием этих перестановок является<center> <img class="tex-graphics" src="https://espresso.codeforces.com/4128a6ff787335449766547609bb326400871a85.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></li><li> Все $$$2$$$-похожие перестановки должны позволять интервалам $$$[1, 3]$$$ и $$$[2, 4]$$$ удерживать свою форму. Поэтому набор всех $$$2$$$-похожих перестановок составляет $$$\{[3, 4, 1, 2], [2, 4, 1, 3]\}$$$. Оптимальным кодированием этих перестановок является<center> <img class="tex-graphics" src="https://espresso.codeforces.com/f8b9494b69f5e6f0f16127113d05109b1cb5c7fa.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></li><li> Все $$$3$$$-похожие перестановки должны позволять интервалы $$$[1, 3]$$$, $$$[2, 4]$$$ и $$$[1, 4]$$$ удерживать свои формы. Поэтому набор всех $$$3$$$-похожих перестановок включает только $$$[2, 4, 1, 3]$$$. Оптимальным кодированием этой перестановки является<center> <img class="tex-graphics" src="https://espresso.codeforces.com/22b16d291f6811e7dcdc4c9b7486ffe65cf52f6f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2246d7d8282fc40c1bc2e10316e99499"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4c1538dfd9494076dc1e10302daf27669dc2adff"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2246d7d8282fc40c1bc2e10316e99499'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1508%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='2246d7d8282fc40c1bc2e10316e99499'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1508">Codeforces Round 715 (Div. 1)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2246d7d8282fc40c1bc2e10316e99499'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1508/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='2246d7d8282fc40c1bc2e10316e99499'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958786"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2246d7d8282fc40c1bc2e10316e99499'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958786"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13506" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13520" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1508">Задачи</a></li> <li><a href="/contest/1508/submit">Отослать</a></li> <li><a href="/contest/1508/my">Мои посылки</a></li> <li><a href="/contest/1508/status">Статус</a></li> <li><a href="/contest/1508/hacks">Взломы</a></li> <li><a href="/contest/1508/room/1">Комната</a></li> <li><a href="/contest/1508/standings">Положение</a></li> <li><a href="/contest/1508/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a5a15da92de0a6c7970c2a6597a76eb7d66d1306"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Оптимальное кодирование</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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>Любимая последовательность чисел Touko — это перестановка $$$a_1, a_2, \dots, a_n$$$ чисел $$$1, 2, \dots, n$$$, и она хочет коллекцию перестановок, похожих на ее любимую перестановку.</p><p>У нее есть коллекция $$$q$$$ отрезков вида $$$[l_i, r_i]$$$ с $$$1 \le l_i \le r_i \le n$$$. Для создания перестановок, похожих на ее любимую перестановку, она придумала следующее определение:</p><ul> <li> Перестановка $$$b_1, b_2, \dots, b_n$$$ позволяет интервалу $$$[l', r']$$$ <span class="tex-font-style-it">удерживать свою форму</span>, если для любой пары целых $$$(x, y)$$$ таких, что $$$l' \le x &lt; y \le r'$$$, неравенство $$$b_x &lt; b_y$$$ выполняется тогда и только тогда, когда $$$a_x &lt; a_y$$$. </li><li> Перестановка $$$b_1, b_2, \dots, b_n$$$ называется <span class="tex-font-style-it">$$$k$$$-похожей</span>, если $$$b$$$ позволяет всем интервалам $$$[l_i, r_i]$$$ для $$$1 \le i \le k$$$ сохранять свою форму. </li></ul><p>Yuu хочет найти все $$$k$$$-похожие перестановки для Touko, но это оказалось очень сложной задачей. Вместо этого Yuu будет <span class="tex-font-style-it">кодировать</span> набор всех $$$k$$$-похожих перестановок ориентированными ациклическими графами (DAG). Yuu также придумала для себя следующие определения:</p><ul> <li> Перестановка $$$b_1, b_2, \dots, b_n$$$ <span class="tex-font-style-it">удовлетворяет</span> DAG $$$G'$$$, если для всех ребер $$$u \to v$$$ в $$$G'$$$ выполняется $$$b_u &lt; b_v$$$. </li><li> <span class="tex-font-style-it">$$$k$$$-кодирование</span> — это DAG $$$G_k$$$ на наборе вершин $$$1, 2, \dots, n$$$ такой, что перестановка $$$b_1, b_2, \dots, b_n$$$ удовлетворяет $$$G_k$$$, если и только если $$$b$$$ является $$$k$$$-похожей. </li></ul><p>Поскольку Yuu сегодня свободна, она хочет выяснить минимальное количество ребер среди всех $$$k$$$-кодирований для каждого $$$k$$$ от $$$1$$$ до $$$q$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 25\,000$$$, $$$1 \le q \le 100\,000$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$, которые образуют перестановку $$$1, 2, \dots, n$$$.</p><p>В $$$i$$$-й из следующих строк $$$q$$$ содержатся два целых числа $$$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>Выведите $$$q$$$ строк. $$$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 2 4 1 3 1 3 2 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 4 3 7 4 8 1 5 2 6 3 6 1 6 3 8 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 5 9 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 10 10 5 1 2 7 3 9 4 6 8 2 2 4 5 6 8 4 10 4 4 2 7 2 2 7 8 3 7 2 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 3 6 6 9 9 9 9 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера:</p><ul><li> Все $$$1$$$-похожие перестановки должны позволять интервалу $$$[1, 3]$$$ удерживать свою форму. Поэтому набор всех $$$1$$$-похожих перестановок составляет $$$\{[3, 4, 2, 1], [3, 4, 1, 2], [2, 4, 1, 3], [2, 3, 1, 4]\}$$$. Оптимальным кодированием этих перестановок является<center> <img class="tex-graphics" src="https://espresso.codeforces.com/4128a6ff787335449766547609bb326400871a85.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></li><li> Все $$$2$$$-похожие перестановки должны позволять интервалам $$$[1, 3]$$$ и $$$[2, 4]$$$ удерживать свою форму. Поэтому набор всех $$$2$$$-похожих перестановок составляет $$$\{[3, 4, 1, 2], [2, 4, 1, 3]\}$$$. Оптимальным кодированием этих перестановок является<center> <img class="tex-graphics" src="https://espresso.codeforces.com/f8b9494b69f5e6f0f16127113d05109b1cb5c7fa.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></li><li> Все $$$3$$$-похожие перестановки должны позволять интервалы $$$[1, 3]$$$, $$$[2, 4]$$$ и $$$[1, 4]$$$ удерживать свои формы. Поэтому набор всех $$$3$$$-похожих перестановок включает только $$$[2, 4, 1, 3]$$$. Оптимальным кодированием этой перестановки является<center> <img class="tex-graphics" src="https://espresso.codeforces.com/22b16d291f6811e7dcdc4c9b7486ffe65cf52f6f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:37</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfb098933a56',t:'MTY5NjY2NzA3Ny4zMzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"]
1509A
1509
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>Sayaka Saeki является членом студенческого совета, в который входит $$$n$$$ других членов (не считая Sayaka). $$$i$$$-й член совета имеет высоту $$$a_i$$$ миллиметров.</p><p>Наступает конец учебного года, и Sayaka хочет сфотографировать всех остальных членов студенческого совета. Будучи трудолюбивой девушкой и перфекционисткой, она хочет выстроить всех членов в ряд таким образом, чтобы количество последовательных пар <span class="tex-font-style-it">фотогеничных</span> членов было <span class="tex-font-style-bf">как можно больше</span>.</p><p>Пара из двух последовательных членов совета $$$u$$$ и $$$v$$$ в строке считается <span class="tex-font-style-it">фотогеничной</span>, если их средний рост — целое число, т.е. $$$\frac{a_u + a_v}{2}$$$ — целое число.</p><p>Помогите Sayaka расположить остальных членов в ряд таким образом, чтобы <span class="tex-font-style-bf">максимизировать</span> количество фотогеничных последовательных пар.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 500$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое $$$n$$$ ($$$2 \le n \le 2000$$$)  — число других членов совета.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$)  — высоты каждого из остальных членов совета в миллиметрах.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите в одной строке $$$n$$$ целых чисел — высоты других членов в порядке, который дает наибольшее количество фотогеничных последовательных пар. Если таких порядков несколько, выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 1 2 3 1 1 1 8 10 9 13 15 3 16 9 13 2 18 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 1 1 1 13 9 13 15 3 9 16 10 9 18 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть одна фотогеничная пара: $$$(1, 1)$$$ — фотогенична, так как $$$\frac{1+1}{2}=1$$$ — целое число, а $$$(1, 2)$$$ — нет, так как $$$\frac{1+2}{2}=1.5$$$ — нецелое число.</p><p>Во втором наборе входных данных обе пары фотогеничны.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9bfdf72a869d23594b4d9b30c4305f7a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="eb488fbeadbb9a19bad4e5e615e986fe72f6d7e9"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='9bfdf72a869d23594b4d9b30c4305f7a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1509%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='9bfdf72a869d23594b4d9b30c4305f7a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1509">Codeforces Round 715 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='9bfdf72a869d23594b4d9b30c4305f7a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1509/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound 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='9bfdf72a869d23594b4d9b30c4305f7a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958787"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9bfdf72a869d23594b4d9b30c4305f7a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958787"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13507" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13521" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1509">Задачи</a></li> <li><a href="/contest/1509/submit">Отослать</a></li> <li><a href="/contest/1509/my">Мои посылки</a></li> <li><a href="/contest/1509/status">Статус</a></li> <li><a href="/contest/1509/hacks">Взломы</a></li> <li><a href="/contest/1509/room/1">Комната</a></li> <li><a href="/contest/1509/standings">Положение</a></li> <li><a href="/contest/1509/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_567623cbf6a0b43ea81a9d225f967f4b4e92f2b6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Sayaka Saeki является членом студенческого совета, в который входит $$$n$$$ других членов (не считая Sayaka). $$$i$$$-й член совета имеет высоту $$$a_i$$$ миллиметров.</p><p>Наступает конец учебного года, и Sayaka хочет сфотографировать всех остальных членов студенческого совета. Будучи трудолюбивой девушкой и перфекционисткой, она хочет выстроить всех членов в ряд таким образом, чтобы количество последовательных пар <span class="tex-font-style-it">фотогеничных</span> членов было <span class="tex-font-style-bf">как можно больше</span>.</p><p>Пара из двух последовательных членов совета $$$u$$$ и $$$v$$$ в строке считается <span class="tex-font-style-it">фотогеничной</span>, если их средний рост — целое число, т.е. $$$\frac{a_u + a_v}{2}$$$ — целое число.</p><p>Помогите Sayaka расположить остальных членов в ряд таким образом, чтобы <span class="tex-font-style-bf">максимизировать</span> количество фотогеничных последовательных пар.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 500$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое $$$n$$$ ($$$2 \le n \le 2000$$$)  — число других членов совета.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$)  — высоты каждого из остальных членов совета в миллиметрах.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите в одной строке $$$n$$$ целых чисел — высоты других членов в порядке, который дает наибольшее количество фотогеничных последовательных пар. Если таких порядков несколько, выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 1 2 3 1 1 1 8 10 9 13 15 3 16 9 13 2 18 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 1 1 1 13 9 13 15 3 9 16 10 9 18 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть одна фотогеничная пара: $$$(1, 1)$$$ — фотогенична, так как $$$\frac{1+1}{2}=1$$$ — целое число, а $$$(1, 2)$$$ — нет, так как $$$\frac{1+2}{2}=1.5$$$ — нецелое число.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:40</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfb93cf8169f',t:'MTY5NjY2NzA4MC45NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*800"]
1509B
1509
B
ru
B. ТМТ документ
<div class="problem-statement"><div class="header"><div class="title">B. ТМТ документ</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У студенческого совета есть общий файл — документ. Каждый день некоторые члены студенческого совета пишут в нем последовательность <span class="tex-font-style-tt">TMT</span>. (сокращение от Towa Maji Tenshi).</p><p>Однако, однажды, члены каким-то образом ввели последовательность в документ одновременно, создав путаницу. Поэтому задача Suguru Doujima — выяснить, не случилось ли сбоя. Ему дается строка длины $$$n$$$, все символы которой — либо <span class="tex-font-style-tt">T</span>, либо <span class="tex-font-style-tt">M</span>, и он хочет выяснить, можно ли разделить ее на некоторое количество подпоследовательностей, каждая из которых равна <span class="tex-font-style-tt">TMT</span>. Каждый символ строки должен принадлежать ровно одной из подпоследовательностей.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$, удалив несколько (возможно, ноль) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$t$$$ ($$$1 \le t \le 5000$$$)  — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$3 \le n &lt; 10^5$$$) — количество символов в строке, введенной в документ. Гарантируется, что $$$n$$$ делится на $$$3$$$.</p><p>Во второй строке каждого набора входных данных находится строка длиной $$$n$$$, состоящая только из символов <span class="tex-font-style-tt">T</span> и <span class="tex-font-style-tt">M</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую <span class="tex-font-style-tt">YES</span>, если описанное разбиение существует, и строку, содержащую <span class="tex-font-style-tt">NO</span>, в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 TMT 3 MTT 6 TMTMTT 6 TMTTTT 6 TTMMTT </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO YES NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных сама строка уже является последовательностью, равной <span class="tex-font-style-tt">TMT</span>.</p><p>В третьем наборе входных данных можно разделить строку на подпоследовательности <span class="tex-font-style-tt"><span class="tex-font-style-bf">TM</span>TMT<span class="tex-font-style-bf">T</span></span>. Подпоследовательности, выделенные жирным шрифтом и нежирным шрифтом, равны <span class="tex-font-style-tt">TMT</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="5060610b72c139f46c9b0f55dc1c0d40"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="eb488fbeadbb9a19bad4e5e615e986fe72f6d7e9"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='5060610b72c139f46c9b0f55dc1c0d40'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1509%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='5060610b72c139f46c9b0f55dc1c0d40'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1509">Codeforces Round 715 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='5060610b72c139f46c9b0f55dc1c0d40'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1509/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='5060610b72c139f46c9b0f55dc1c0d40'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958788"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5060610b72c139f46c9b0f55dc1c0d40'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958788"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13507" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13521" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1509">Задачи</a></li> <li><a href="/contest/1509/submit">Отослать</a></li> <li><a href="/contest/1509/my">Мои посылки</a></li> <li><a href="/contest/1509/status">Статус</a></li> <li><a href="/contest/1509/hacks">Взломы</a></li> <li><a href="/contest/1509/room/1">Комната</a></li> <li><a href="/contest/1509/standings">Положение</a></li> <li><a href="/contest/1509/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ae10c50170837bf2a6e6d79f2b8f07366a2c7b29"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. ТМТ документ</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У студенческого совета есть общий файл — документ. Каждый день некоторые члены студенческого совета пишут в нем последовательность <span class="tex-font-style-tt">TMT</span>. (сокращение от Towa Maji Tenshi).</p><p>Однако, однажды, члены каким-то образом ввели последовательность в документ одновременно, создав путаницу. Поэтому задача Suguru Doujima — выяснить, не случилось ли сбоя. Ему дается строка длины $$$n$$$, все символы которой — либо <span class="tex-font-style-tt">T</span>, либо <span class="tex-font-style-tt">M</span>, и он хочет выяснить, можно ли разделить ее на некоторое количество подпоследовательностей, каждая из которых равна <span class="tex-font-style-tt">TMT</span>. Каждый символ строки должен принадлежать ровно одной из подпоследовательностей.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$, удалив несколько (возможно, ноль) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится целое число $$$t$$$ ($$$1 \le t \le 5000$$$)  — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$3 \le n &lt; 10^5$$$) — количество символов в строке, введенной в документ. Гарантируется, что $$$n$$$ делится на $$$3$$$.</p><p>Во второй строке каждого набора входных данных находится строка длиной $$$n$$$, состоящая только из символов <span class="tex-font-style-tt">T</span> и <span class="tex-font-style-tt">M</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую <span class="tex-font-style-tt">YES</span>, если описанное разбиение существует, и строку, содержащую <span class="tex-font-style-tt">NO</span>, в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 TMT 3 MTT 6 TMTMTT 6 TMTTTT 6 TTMMTT </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO YES NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных сама строка уже является последовательностью, равной <span class="tex-font-style-tt">TMT</span>.</p><p>В третьем наборе входных данных можно разделить строку на подпоследовательности <span class="tex-font-style-tt"><span class="tex-font-style-bf">TM</span>TMT<span class="tex-font-style-bf">T</span></span>. Подпоследовательности, выделенные жирным шрифтом и нежирным шрифтом, равны <span class="tex-font-style-tt">TMT</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:42</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfcf98819d45',t:'MTY5NjY2NzA4Mi4zNDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1100"]
1509C
1509
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>Совет состоит из $$$n$$$ членов. Они будут бегать один за другим в забеге, скорость члена $$$i$$$ равна $$$s_i$$$. <span class="tex-font-style-it">Расхождение</span> $$$d_i$$$ $$$i$$$-го этапа — разница между максимальной и минимальной скоростью бега среди первых $$$i$$$ членов, которые участвовали в забеге. Формально, если $$$a_i$$$ обозначает скорость $$$i$$$-го участника, участвовавшего в забеге, то $$$d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i)$$$.</p><p>Вы хотите минимизировать сумму расхождений $$$d_1 + d_2 + \dots + d_n$$$. Для этого можно изменить порядок, в котором будут бежать участники. Какова минимально возможная сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2000$$$)  — количество членов студенческого совета.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$)  — скорости членов совета.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — минимально возможное значение $$$d_1 + d_2 + \dots + d_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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 6 3 3 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 104 943872923 6589 889921234 1000000000 69 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2833800505 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, мы можем выбрать, чтобы третий член бежал первым, затем первый, и, наконец, второй. Таким образом, $$$a_1 = 2$$$, $$$a_2 = 3$$$, а $$$a_3 = 1$$$. Тогда получаем:</p><ul> <li> $$$d_1 = \max(2) - \min(2) = 2 - 2 = 0$$$. </li><li> $$$d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1$$$. </li><li> $$$d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2$$$. </li></ul><p>Полученная сумма равна $$$d_1 + d_2 + d_3 = 0 + 1 + 2 = 3$$$. Можно показать, что меньшего значения добиться невозможно.</p><p>Во втором примере единственная возможная перестановка дает $$$d_1 = 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="e31b3103b8d8c7b400bac2b72771ba9d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="eb488fbeadbb9a19bad4e5e615e986fe72f6d7e9"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e31b3103b8d8c7b400bac2b72771ba9d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1509%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='e31b3103b8d8c7b400bac2b72771ba9d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1509">Codeforces Round 715 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e31b3103b8d8c7b400bac2b72771ba9d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1509/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='e31b3103b8d8c7b400bac2b72771ba9d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958789"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e31b3103b8d8c7b400bac2b72771ba9d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958789"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13507" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13521" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1509">Задачи</a></li> <li><a href="/contest/1509/submit">Отослать</a></li> <li><a href="/contest/1509/my">Мои посылки</a></li> <li><a href="/contest/1509/status">Статус</a></li> <li><a href="/contest/1509/hacks">Взломы</a></li> <li><a href="/contest/1509/room/1">Комната</a></li> <li><a href="/contest/1509/standings">Положение</a></li> <li><a href="/contest/1509/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9c42490ee2eaa78c2092adbbd980e43ef919de16"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Совет состоит из $$$n$$$ членов. Они будут бегать один за другим в забеге, скорость члена $$$i$$$ равна $$$s_i$$$. <span class="tex-font-style-it">Расхождение</span> $$$d_i$$$ $$$i$$$-го этапа — разница между максимальной и минимальной скоростью бега среди первых $$$i$$$ членов, которые участвовали в забеге. Формально, если $$$a_i$$$ обозначает скорость $$$i$$$-го участника, участвовавшего в забеге, то $$$d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i)$$$.</p><p>Вы хотите минимизировать сумму расхождений $$$d_1 + d_2 + \dots + d_n$$$. Для этого можно изменить порядок, в котором будут бежать участники. Какова минимально возможная сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится единственное целое число $$$n$$$ ($$$1 \le n \le 2000$$$)  — количество членов студенческого совета.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$)  — скорости членов совета.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число  — минимально возможное значение $$$d_1 + d_2 + \dots + d_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 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 6 3 3 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 104 943872923 6589 889921234 1000000000 69 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2833800505 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, мы можем выбрать, чтобы третий член бежал первым, затем первый, и, наконец, второй. Таким образом, $$$a_1 = 2$$$, $$$a_2 = 3$$$, а $$$a_3 = 1$$$. Тогда получаем:</p><ul> <li> $$$d_1 = \max(2) - \min(2) = 2 - 2 = 0$$$. </li><li> $$$d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1$$$. </li><li> $$$d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2$$$. </li></ul><p>Полученная сумма равна $$$d_1 + d_2 + d_3 = 0 + 1 + 2 = 3$$$. Можно показать, что меньшего значения добиться невозможно.</p><p>Во втором примере единственная возможная перестановка дает $$$d_1 = 0$$$, поэтому минимально возможный результат равен $$$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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:43</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfd869443a89',t:'MTY5NjY2NzA4My43MzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1800"]
1509D
1509
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>Бинарная строка — это строка, содержащая только символы <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Koyomi Kanou усердно работает над своей мечтой стать писательницей. Чтобы попрактиковаться, она решила принять участие в <span class="tex-font-style-it">Конкурсе по Написанию Бинарных Романов</span>. Указание к конкурсу состоит из трёх бинарных строк длины $$$2n$$$. Корректным романом для конкурса является бинарная строка длины не более $$$3n$$$, содержащая в качестве подпоследовательностей <span class="tex-font-style-bf">не менее двух</span> из трёх данных строк.</p><p>Koyomi только что получила три строки — указание от организаторов конкурса. Помогите ей написать корректный роман для конкурса.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$, удалив несколько (возможно, ноль) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>Каждая из следующих трех строк содержит бинарную строку длины $$$2n$$$. Гарантируется, что эти три строки попарно различны.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую бинарную строку длины не более $$$3n$$$, которая в качестве подпоследовательностей содержит как минимум две из заданных бинарных строк.</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 1 00 11 01 3 011001 111010 010001 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 010 011001010 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных бинарные строки <span class="tex-font-style-tt">00</span> и <span class="tex-font-style-tt">01</span> являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">0</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">01</span>0</span>. Обратите внимание, что <span class="tex-font-style-tt">11</span> не является подпоследовательностью выходной строки, но это не требуется.</p><p>Во втором наборе входных данных все три входных строки являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011</span>0<span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">01</span>0</span>, <span class="tex-font-style-tt">0<span class="tex-font-style-bf">11</span>00<span class="tex-font-style-bf">1010</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">100</span>1<span class="tex-font-style-bf">01</span>0</span>.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="782073a10e3c0602914d5994651c7e45"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="eb488fbeadbb9a19bad4e5e615e986fe72f6d7e9"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='782073a10e3c0602914d5994651c7e45'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1509%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='782073a10e3c0602914d5994651c7e45'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1509">Codeforces Round 715 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='782073a10e3c0602914d5994651c7e45'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1509/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1900 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='782073a10e3c0602914d5994651c7e45'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958790"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='782073a10e3c0602914d5994651c7e45'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958790"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13507" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13521" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1509">Задачи</a></li> <li><a href="/contest/1509/submit">Отослать</a></li> <li><a href="/contest/1509/my">Мои посылки</a></li> <li><a href="/contest/1509/status">Статус</a></li> <li><a href="/contest/1509/hacks">Взломы</a></li> <li><a href="/contest/1509/room/1">Комната</a></li> <li><a href="/contest/1509/standings">Положение</a></li> <li><a href="/contest/1509/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b53e42af71ef12b00c579f15d74b6d7798b2c870"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Бинарная строка — это строка, содержащая только символы <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Koyomi Kanou усердно работает над своей мечтой стать писательницей. Чтобы попрактиковаться, она решила принять участие в <span class="tex-font-style-it">Конкурсе по Написанию Бинарных Романов</span>. Указание к конкурсу состоит из трёх бинарных строк длины $$$2n$$$. Корректным романом для конкурса является бинарная строка длины не более $$$3n$$$, содержащая в качестве подпоследовательностей <span class="tex-font-style-bf">не менее двух</span> из трёх данных строк.</p><p>Koyomi только что получила три строки — указание от организаторов конкурса. Помогите ей написать корректный роман для конкурса.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$, удалив несколько (возможно, ноль) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>Каждая из следующих трех строк содержит бинарную строку длины $$$2n$$$. Гарантируется, что эти три строки попарно различны.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую бинарную строку длины не более $$$3n$$$, которая в качестве подпоследовательностей содержит как минимум две из заданных бинарных строк.</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 1 00 11 01 3 011001 111010 010001 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 010 011001010 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных бинарные строки <span class="tex-font-style-tt">00</span> и <span class="tex-font-style-tt">01</span> являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">0</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">01</span>0</span>. Обратите внимание, что <span class="tex-font-style-tt">11</span> не является подпоследовательностью выходной строки, но это не требуется.</p><p>Во втором наборе входных данных все три входных строки являются подпоследовательностями выходной строки: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011</span>0<span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">01</span>0</span>, <span class="tex-font-style-tt">0<span class="tex-font-style-bf">11</span>00<span class="tex-font-style-bf">1010</span></span> и <span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>1<span class="tex-font-style-bf">100</span>1<span class="tex-font-style-bf">01</span>0</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:45</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfe119303374',t:'MTY5NjY2NzA4NS4wNzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1900"]
1509E
1509
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>Seiji Maki не только любит наблюдать за развитием отношений, он также любит наблюдать за последовательностями чисел, особенно перестановками. Сегодня он смотрит на <span class="tex-font-style-it">почти отсортированные</span> перестановки.</p><p>Перестановка $$$a_1, a_2, \dots, a_n$$$ чисел $$$1, 2, \dots, n$$$ считается <span class="tex-font-style-it">почти отсортированной</span>, если условие $$$a_{i + 1} \ge a_i - 1$$$ выполняется для всех $$$i$$$ от $$$1$$$ до $$$n - 1$$$ включительно.</p><p>Maki рассматривает список всех почти отсортированных перестановок чисел $$$1, 2, \dots, n$$$, приведенных в лексикографическом порядке, и хочет найти в этом списке перестановку $$$k$$$-ю. Можете ли вы помочь ему найти такую перестановку?</p><p>Перестановка $$$p$$$ лексикографически меньше перестановки $$$q$$$, если и только если выполняется следующее:</p><ul><li> в первой позиции, где $$$p$$$ и $$$q$$$ различны, в перестановке $$$p$$$ элемент меньше, чем соответствующий элемент в $$$q$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки, содержащей два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le k \le 10^{18}$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую $$$k$$$-ю почти отсортированную перестановку длины $$$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> 5 1 1 1 2 3 3 6 5 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого и второго набора входных данных список почти отсортированных перестановок с $$$n = 1$$$ составляет $$$\{[1]\}$$$.</p><p>Для третьего и пятого набора входных данных список почти отсортированных перестановок с $$$n = 3$$$ составляет $$$\{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a6be576eae84d40fd550a6d79632ebf9"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="eb488fbeadbb9a19bad4e5e615e986fe72f6d7e9"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a6be576eae84d40fd550a6d79632ebf9'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1509%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='a6be576eae84d40fd550a6d79632ebf9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1509">Codeforces Round 715 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a6be576eae84d40fd550a6d79632ebf9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1509/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='a6be576eae84d40fd550a6d79632ebf9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958791"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a6be576eae84d40fd550a6d79632ebf9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958791"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13507" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13521" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1509">Задачи</a></li> <li><a href="/contest/1509/submit">Отослать</a></li> <li><a href="/contest/1509/my">Мои посылки</a></li> <li><a href="/contest/1509/status">Статус</a></li> <li><a href="/contest/1509/hacks">Взломы</a></li> <li><a href="/contest/1509/room/1">Комната</a></li> <li><a href="/contest/1509/standings">Положение</a></li> <li><a href="/contest/1509/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9f84a0daf5c9b228cdf17c1595cf6c38fe1baa7e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Seiji Maki не только любит наблюдать за развитием отношений, он также любит наблюдать за последовательностями чисел, особенно перестановками. Сегодня он смотрит на <span class="tex-font-style-it">почти отсортированные</span> перестановки.</p><p>Перестановка $$$a_1, a_2, \dots, a_n$$$ чисел $$$1, 2, \dots, n$$$ считается <span class="tex-font-style-it">почти отсортированной</span>, если условие $$$a_{i + 1} \ge a_i - 1$$$ выполняется для всех $$$i$$$ от $$$1$$$ до $$$n - 1$$$ включительно.</p><p>Maki рассматривает список всех почти отсортированных перестановок чисел $$$1, 2, \dots, n$$$, приведенных в лексикографическом порядке, и хочет найти в этом списке перестановку $$$k$$$-ю. Можете ли вы помочь ему найти такую перестановку?</p><p>Перестановка $$$p$$$ лексикографически меньше перестановки $$$q$$$, если и только если выполняется следующее:</p><ul><li> в первой позиции, где $$$p$$$ и $$$q$$$ различны, в перестановке $$$p$$$ элемент меньше, чем соответствующий элемент в $$$q$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1\le t\le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки, содержащей два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le k \le 10^{18}$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую $$$k$$$-ю почти отсортированную перестановку длины $$$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> 5 1 1 1 2 3 3 6 5 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого и второго набора входных данных список почти отсортированных перестановок с $$$n = 1$$$ составляет $$$\{[1]\}$$$.</p><p>Для третьего и пятого набора входных данных список почти отсортированных перестановок с $$$n = 3$$$ составляет $$$\{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:46</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bfe998f44d90',t:'MTY5NjY2NzA4Ni4zODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1800"]
1509F
1509
F
ru
F. Завершите MST
<div class="problem-statement"><div class="header"><div class="title">F. Завершите MST</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>Как преподаватель, Riko Hakozaki часто помогает ученикам в решении задач по различным предметам. Сегодня ее попросили помочь с задачей по программированию, которая заключается в следующем.</p><p>Вам выдается неориентированный полный граф с $$$n$$$ вершинами, где для некоторых ребер заданы положительные веса, а для остальных нет. Вам нужно назначить всем еще не назначенным рёбрам <span class="tex-font-style-bf">неотрицательные веса</span> так, чтобы у получившегося графа <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">XOR (побитовое исключающее ИЛИ)</a> всех весов был равен $$$0$$$.</p><p>Определим <span class="tex-font-style-it">уродство</span> полного графа как вес его <a href="https://ru.wikipedia.org/wiki/Минимальное_остовное_дерево">минимального остовного дерева</a>, где вес остовного дерева равен сумме весов его рёбер. Нужно назначить веса так, чтобы уродство получившегося графа было как можно меньше.</p><p>Напомним, что неориентированный полный граф с $$$n$$$ вершинами содержит все рёбра $$$(u, v)$$$ с $$$1 \le u &lt; v \le n$$$; такой граф имеет $$$\frac{n(n-1)}{2}$$$ рёбер.</p><p>Она не знает, как решить эту задачу, поэтому просит вас решить ее за нее.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2} - 1)$$$)  — количество вершин и количество предварительно назначенных рёбер. Гарантируется, что есть по крайней мере одно неназначенное ребро.</p><p>$$$i$$$-я из следующих строк $$$m$$$ содержит три целых числа $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u \ne v$$$, $$$1 \le w_i &lt; 2^{30}$$$), обознаающие ребро от $$$u_i$$$ до $$$v_i$$$, которому был назначен вес $$$w_i$$$. Ни одно ребро не появляется во вводе более одного раза.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите в одной строке одно целое число  — минимальное уродство среди всех возможных назначений весов с XOR суммой равной $$$0$$$.</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 2 1 14 1 4 14 3 2 15 4 3 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a7a280c2f88b120ff0839966d25330c968719a1c.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="a5823e30516afb2e140604a44288e3ad"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="eb488fbeadbb9a19bad4e5e615e986fe72f6d7e9"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a5823e30516afb2e140604a44288e3ad'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1509%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='a5823e30516afb2e140604a44288e3ad'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1509">Codeforces Round 715 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a5823e30516afb2e140604a44288e3ad'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1509/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='a5823e30516afb2e140604a44288e3ad'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="958792"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a5823e30516afb2e140604a44288e3ad'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="958792"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89639" title="Codeforces Round #715" target="_blank">Codeforces Round #715 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13507" resourceName="Codeforces Round #715" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89644" title="Codeforces Round #715 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13521" resourceName="Codeforces Round #715 Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1509">Задачи</a></li> <li><a href="/contest/1509/submit">Отослать</a></li> <li><a href="/contest/1509/my">Мои посылки</a></li> <li><a href="/contest/1509/status">Статус</a></li> <li><a href="/contest/1509/hacks">Взломы</a></li> <li><a href="/contest/1509/room/1">Комната</a></li> <li><a href="/contest/1509/standings">Положение</a></li> <li><a href="/contest/1509/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_54f0b94a2015f5a5c17375a3fdae59df7837375e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Завершите MST</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>Как преподаватель, Riko Hakozaki часто помогает ученикам в решении задач по различным предметам. Сегодня ее попросили помочь с задачей по программированию, которая заключается в следующем.</p><p>Вам выдается неориентированный полный граф с $$$n$$$ вершинами, где для некоторых ребер заданы положительные веса, а для остальных нет. Вам нужно назначить всем еще не назначенным рёбрам <span class="tex-font-style-bf">неотрицательные веса</span> так, чтобы у получившегося графа <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">XOR (побитовое исключающее ИЛИ)</a> всех весов был равен $$$0$$$.</p><p>Определим <span class="tex-font-style-it">уродство</span> полного графа как вес его <a href="https://ru.wikipedia.org/wiki/Минимальное_остовное_дерево">минимального остовного дерева</a>, где вес остовного дерева равен сумме весов его рёбер. Нужно назначить веса так, чтобы уродство получившегося графа было как можно меньше.</p><p>Напомним, что неориентированный полный граф с $$$n$$$ вершинами содержит все рёбра $$$(u, v)$$$ с $$$1 \le u &lt; v \le n$$$; такой граф имеет $$$\frac{n(n-1)}{2}$$$ рёбер.</p><p>Она не знает, как решить эту задачу, поэтому просит вас решить ее за нее.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2} - 1)$$$)  — количество вершин и количество предварительно назначенных рёбер. Гарантируется, что есть по крайней мере одно неназначенное ребро.</p><p>$$$i$$$-я из следующих строк $$$m$$$ содержит три целых числа $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u \ne v$$$, $$$1 \le w_i &lt; 2^{30}$$$), обознаающие ребро от $$$u_i$$$ до $$$v_i$$$, которому был назначен вес $$$w_i$$$. Ни одно ребро не появляется во вводе более одного раза.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите в одной строке одно целое число  — минимальное уродство среди всех возможных назначений весов с XOR суммой равной $$$0$$$.</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 2 1 14 1 4 14 3 2 15 4 3 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a7a280c2f88b120ff0839966d25330c968719a1c.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:47</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bff19ae69d98',t:'MTY5NjY2NzA4Ny42NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2500"]
1510A
1510
A
ru
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="85930b74fdc2062b61ec04c657df89a7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Приложения - 2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Приложения - 2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred) - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='85930b74fdc2062b61ec04c657df89a7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showMessage("Не найдено условие задачи на вашем языке, однако вы можете скачать условия для всех задач соревнования в одном файле"); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%2Fattachments">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='85930b74fdc2062b61ec04c657df89a7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='85930b74fdc2062b61ec04c657df89a7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Условия <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <tr> <th>Название</th> <th>Язык</th> <th>Действия</th> </tr> <tr> <td> Statements (PDF) <div class="small notice" style="margin-top: 1em;"> Файл с условиями может содержать неактуальные ограничения по времени и памяти. Перейдите на страницу "Задачи" для просмотра актуальных ограничений. </div> </td> <td> английский </td> <td> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" target="_blank">Скачать</a> </td> </tr> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> <div style="display: none;"> <form id="deleteAttachmentForm" action=""><input type='hidden' name='csrf_token' value='85930b74fdc2062b61ec04c657df89a7'/> <input type="hidden" name="action" value="delete"/> <input type="hidden" name="contestId" value="1510"/> <input type="hidden" name="attachmentId" value=""/> </form> </div> <script type="text/javascript"> $(document).ready(function () { $("a.deleteAttachmentLink").click(function () { var attachmentRepresentation = $(this).attr("attachmentRepresentation"); var confirmationMessage = "Вы уверены, что хотите удалить \'%%attachmentRepresentation%%\'?" .replace("%%attachmentRepresentation%%", attachmentRepresentation); var attachmentId = $(this).attr("attachmentId"); Codeforces.confirm(confirmationMessage, function () { var deleteAttachmentForm = $("#deleteAttachmentForm"); deleteAttachmentForm.find("input[name=attachmentId]").val(attachmentId); deleteAttachmentForm.submit(); }, function () { }, "Да", "Нет" ); return false; }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:49</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124bffc6f2d166c',t:'MTY5NjY2NzA4OS40NjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
""
""
nan
1510B
1510
B
ru
B. Button Lock
<div class="problem-statement"><div class="header"><div class="title">B. Button Lock</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has $$$d$$$ buttons with digits from $$$0$$$ to $$$d - 1$$$. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a "RESET" button — pressing it pops up all other buttons. Initially, no buttons are pushed down.</p><p>The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are $$$n$$$ possible passwords for this particular lock. </p><p>Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains two integers $$$d$$$ and $$$n$$$ ($$$1 \le d \le 10$$$; $$$1 \le n \le 2^d - 1$$$). Next $$$n$$$ lines describe possible passwords. Each line contains a string $$$s_i$$$ of $$$d$$$ zeros and ones: for all $$$j$$$ from $$$1$$$ to $$$d$$$ the $$$j$$$-th character is <span class="tex-font-style-tt">1</span> iff the button with the digit $$$j - 1$$$ must be pushed down.</p><p>All strings $$$s_i$$$ are different, and each string contains at least one <span class="tex-font-style-tt">1</span>.</p></div><div class="output-specification"><div class="section-title">Output</div><p>On the first line, print the number $$$k$$$ — the minimum number of button presses. On the second line, print $$$k$$$ tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press "RESET", print "<span class="tex-font-style-tt">R</span>".</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 2 2 10 11 </pre></div><div class="output"><div class="title">Output</div><pre> 2 0 1 </pre></div><div class="input"><div class="title">Input</div><pre> 3 4 001 111 101 011 </pre></div><div class="output"><div class="title">Output</div><pre> 6 2 0 R 1 2 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the second example, the sequence <span class="tex-font-style-tt">1 2 R 2 0 1</span> is also possible.</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="821ce56368c3545a989e0126a70c948d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='821ce56368c3545a989e0126a70c948d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%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='821ce56368c3545a989e0126a70c948d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='821ce56368c3545a989e0126a70c948d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах"> паросочетания </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Потоки в графах"> потоки </span> </div> <div class="roundbox borderTopRound 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='821ce56368c3545a989e0126a70c948d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946212"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='821ce56368c3545a989e0126a70c948d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946212"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4b5f212be4dc956bd84b007c2394a6495ac11871"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Button Lock</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>You are standing in front of the room with great treasures. The only thing stopping you is the door with a push-button combination lock. This lock has $$$d$$$ buttons with digits from $$$0$$$ to $$$d - 1$$$. Whenever you press a button, it stays pushed down. You can not pop back up just one button, but there is a &quot;RESET&quot; button — pressing it pops up all other buttons. Initially, no buttons are pushed down.</p><p>The door instantly opens when some specific set of digits is pushed down. Sadly, you don't know the password for it. Having read the documentation for this specific lock, you found out that there are $$$n$$$ possible passwords for this particular lock. </p><p>Find the shortest sequence of button presses, such that all possible passwords appear at least once during its execution. Any shortest correct sequence of button presses will be accepted.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains two integers $$$d$$$ and $$$n$$$ ($$$1 \le d \le 10$$$; $$$1 \le n \le 2^d - 1$$$). Next $$$n$$$ lines describe possible passwords. Each line contains a string $$$s_i$$$ of $$$d$$$ zeros and ones: for all $$$j$$$ from $$$1$$$ to $$$d$$$ the $$$j$$$-th character is <span class="tex-font-style-tt">1</span> iff the button with the digit $$$j - 1$$$ must be pushed down.</p><p>All strings $$$s_i$$$ are different, and each string contains at least one <span class="tex-font-style-tt">1</span>.</p></div><div class="output-specification"><div class="section-title">Output</div><p>On the first line, print the number $$$k$$$ — the minimum number of button presses. On the second line, print $$$k$$$ tokens, describing the sequence. Whenever you press a button with a digit, print that digit. Whenever you press &quot;RESET&quot;, print &quot;<span class="tex-font-style-tt">R</span>&quot;.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 2 2 10 11 </pre></div><div class="output"><div class="title">Output</div><pre> 2 0 1 </pre></div><div class="input"><div class="title">Input</div><pre> 3 4 001 111 101 011 </pre></div><div class="output"><div class="title">Output</div><pre> 6 2 0 R 1 2 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the second example, the sequence <span class="tex-font-style-tt">1 2 R 2 0 1</span> is also possible.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:50</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c004bd1f3aa7',t:'MTY5NjY2NzA5MC44MTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u043e\u0442\u043e\u043a\u0438", "*2600"]
1510C
1510
C
ru
C. Cactus Not Enough
<div class="problem-statement"><div class="header"><div class="title">C. Cactus Not Enough</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>There was no problem about a cactus at the NERC 2020 online round. That's a bad mistake, so judges decided to fix it. You shall not pass to the World Finals 2021 without solving a problem about a cactus!</p><p>A <span class="tex-font-style-underline">cactus</span> is a connected undirected graph in which every edge lies on at most one simple cycle. Intuitively, a cactus is a generalization of a tree where some cycles are allowed. Multiedges (multiple edges between a pair of vertices) and loops (edges that connect a vertex to itself) are not allowed in a cactus. </p><p>Cher has got a cactus. She calls cactus <span class="tex-font-style-underline">strong</span> if it is impossible to add an edge to it in such a way that it still remains a cactus. But Cher thinks her cactus is not strong enough. She wants to add the smallest possible number of edges to it to make it strong, i. e. to create a new cactus with the same vertices, so that the original cactus is a subgraph of the new one, and it is impossible to add another edge to it so that the graph remains a cactus. Cher hired you to do this job for her. So... it's on you!</p></div><div class="input-specification"><div class="section-title">Input</div><p>The input consists of one or more independent test cases.</p><p>The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le m \le 10^5$$$), where $$$n$$$ is the number of vertices in the graph. Vertices are numbered from $$$1$$$ to $$$n$$$. Edges of the graph are represented by a set of edge-distinct paths, where $$$m$$$ is the number of such paths. </p><p>Each of the following $$$m$$$ lines contains a path in the graph. A path starts with an integer number $$$s_i$$$ ($$$2 \le s_i \le 1000$$$) followed by $$$s_i$$$ integers from $$$1$$$ to $$$n$$$. These $$$s_i$$$ integers represent vertices of a path. Adjacent vertices in a path are distinct. The path can go through the same vertex multiple times, but every edge is traversed exactly once in the whole test case. There are no multiedges in the graph (there is at most one edge between any two vertices).</p><p>The last line of the input after all test cases always contains two zeros. It does <span class="tex-font-style-bf">not</span> define a test case. It just marks the end of the input and does not require any output.</p><p>All graphs in the input are cacti. The total sum of all values of $$$n$$$ and the total sum of all values of $$$m$$$ throughout the input both do not exceed $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>For each test case, first output the line with the minimal possible number of additional edges $$$A$$$. Then output $$$A$$$ lines, each describing one edge as $$$u_i$$$ $$$v_i$$$, where $$$u_i$$$ and $$$v_i$$$ are the numbers of vertices to connect. After adding these edges, the resulting graph must be a strong cactus.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 6 1 7 1 2 5 6 2 3 4 3 1 4 1 2 3 1 5 2 3 1 3 5 3 1 2 4 7 2 6 1 2 3 4 5 3 3 6 5 7 0 0 </pre></div><div class="output"><div class="title">Output</div><pre> 1 1 4 0 1 5 4 2 1 3 6 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="67a0f6666be1ac4a19e6485a82fe7ae8"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='67a0f6666be1ac4a19e6485a82fe7ae8'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%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='67a0f6666be1ac4a19e6485a82fe7ae8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='67a0f6666be1ac4a19e6485a82fe7ae8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах"> паросочетания </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound 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='67a0f6666be1ac4a19e6485a82fe7ae8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946213"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='67a0f6666be1ac4a19e6485a82fe7ae8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946213"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_494ee5372e7ca7b655cc392fba96f899becba83f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Cactus Not Enough</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>There was no problem about a cactus at the NERC 2020 online round. That's a bad mistake, so judges decided to fix it. You shall not pass to the World Finals 2021 without solving a problem about a cactus!</p><p>A <span class="tex-font-style-underline">cactus</span> is a connected undirected graph in which every edge lies on at most one simple cycle. Intuitively, a cactus is a generalization of a tree where some cycles are allowed. Multiedges (multiple edges between a pair of vertices) and loops (edges that connect a vertex to itself) are not allowed in a cactus. </p><p>Cher has got a cactus. She calls cactus <span class="tex-font-style-underline">strong</span> if it is impossible to add an edge to it in such a way that it still remains a cactus. But Cher thinks her cactus is not strong enough. She wants to add the smallest possible number of edges to it to make it strong, i. e. to create a new cactus with the same vertices, so that the original cactus is a subgraph of the new one, and it is impossible to add another edge to it so that the graph remains a cactus. Cher hired you to do this job for her. So... it's on you!</p></div><div class="input-specification"><div class="section-title">Input</div><p>The input consists of one or more independent test cases.</p><p>The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le m \le 10^5$$$), where $$$n$$$ is the number of vertices in the graph. Vertices are numbered from $$$1$$$ to $$$n$$$. Edges of the graph are represented by a set of edge-distinct paths, where $$$m$$$ is the number of such paths. </p><p>Each of the following $$$m$$$ lines contains a path in the graph. A path starts with an integer number $$$s_i$$$ ($$$2 \le s_i \le 1000$$$) followed by $$$s_i$$$ integers from $$$1$$$ to $$$n$$$. These $$$s_i$$$ integers represent vertices of a path. Adjacent vertices in a path are distinct. The path can go through the same vertex multiple times, but every edge is traversed exactly once in the whole test case. There are no multiedges in the graph (there is at most one edge between any two vertices).</p><p>The last line of the input after all test cases always contains two zeros. It does <span class="tex-font-style-bf">not</span> define a test case. It just marks the end of the input and does not require any output.</p><p>All graphs in the input are cacti. The total sum of all values of $$$n$$$ and the total sum of all values of $$$m$$$ throughout the input both do not exceed $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>For each test case, first output the line with the minimal possible number of additional edges $$$A$$$. Then output $$$A$$$ lines, each describing one edge as $$$u_i$$$ $$$v_i$$$, where $$$u_i$$$ and $$$v_i$$$ are the numbers of vertices to connect. After adding these edges, the resulting graph must be a strong cactus.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 6 1 7 1 2 5 6 2 3 4 3 1 4 1 2 3 1 5 2 3 1 3 5 3 1 2 4 7 2 6 1 2 3 4 5 3 3 6 5 7 0 0 </pre></div><div class="output"><div class="title">Output</div><pre> 1 1 4 0 1 5 4 2 1 3 6 7 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:52</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c00d3bda16df',t:'MTY5NjY2NzA5Mi4xNTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\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", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2900"]
1510D
1510
D
ru
D. Digits
<div class="problem-statement"><div class="header"><div class="title">D. Digits</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>Diana loves playing with numbers. She's got $$$n$$$ cards with positive integer numbers $$$a_i$$$ written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers $$$a_i$$$ written on them.</p><p>Diana is happy when the product of the numbers ends with her favorite digit $$$d$$$. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is $$$d$$$. Please, help her.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains the integers $$$n$$$ and $$$d$$$ ($$$1\le n\le 10^5$$$, $$$0\le d\le 9$$$). The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1\le a_i\le 1000$$$). </p></div><div class="output-specification"><div class="section-title">Output</div><p>On the first line, print the number of chosen cards $$$k$$$ ($$$1\le k\le n$$$). On the next line, print the numbers written on the chosen cards in any order. </p><p>If it is impossible to choose a subset of cards with the product that ends with the digit $$$d$$$, print the single line with $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 6 4 4 11 8 2 1 13 </pre></div><div class="output"><div class="title">Output</div><pre> 5 1 2 4 11 13 </pre></div><div class="input"><div class="title">Input</div><pre> 3 1 2 4 6 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 5 7 1 3 1 5 3 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 6 3 8 9 4 17 11 5 </pre></div><div class="output"><div class="title">Output</div><pre> 3 9 11 17 </pre></div><div class="input"><div class="title">Input</div><pre> 5 6 2 2 2 2 2 </pre></div><div class="output"><div class="title">Output</div><pre> 4 2 2 2 2 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first example, $$$1 \times 2 \times 4 \times 11 \times 13 = 1144$$$, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.</p><p>In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.</p><p>In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.</p><p>In the fourth example, $$$9 \times 11 \times 17 = 1683$$$, which ends with the digit 3. </p><p>In the fifth example, $$$2 \times 2 \times 2 \times 2 = 16$$$, which ends with the digit 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="1cafa80a33e93ff2c7cc0fb276ce1186"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='1cafa80a33e93ff2c7cc0fb276ce1186'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%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='1cafa80a33e93ff2c7cc0fb276ce1186'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1cafa80a33e93ff2c7cc0fb276ce1186'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='1cafa80a33e93ff2c7cc0fb276ce1186'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946214"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1cafa80a33e93ff2c7cc0fb276ce1186'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946214"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0200625fb694c7a106a7b62ce525d27f78d95307"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Digits</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>Diana loves playing with numbers. She's got $$$n$$$ cards with positive integer numbers $$$a_i$$$ written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers $$$a_i$$$ written on them.</p><p>Diana is happy when the product of the numbers ends with her favorite digit $$$d$$$. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is $$$d$$$. Please, help her.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains the integers $$$n$$$ and $$$d$$$ ($$$1\le n\le 10^5$$$, $$$0\le d\le 9$$$). The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1\le a_i\le 1000$$$). </p></div><div class="output-specification"><div class="section-title">Output</div><p>On the first line, print the number of chosen cards $$$k$$$ ($$$1\le k\le n$$$). On the next line, print the numbers written on the chosen cards in any order. </p><p>If it is impossible to choose a subset of cards with the product that ends with the digit $$$d$$$, print the single line with $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 6 4 4 11 8 2 1 13 </pre></div><div class="output"><div class="title">Output</div><pre> 5 1 2 4 11 13 </pre></div><div class="input"><div class="title">Input</div><pre> 3 1 2 4 6 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 5 7 1 3 1 5 3 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 6 3 8 9 4 17 11 5 </pre></div><div class="output"><div class="title">Output</div><pre> 3 9 11 17 </pre></div><div class="input"><div class="title">Input</div><pre> 5 6 2 2 2 2 2 </pre></div><div class="output"><div class="title">Output</div><pre> 4 2 2 2 2 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first example, $$$1 \times 2 \times 4 \times 11 \times 13 = 1144$$$, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.</p><p>In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.</p><p>In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.</p><p>In the fourth example, $$$9 \times 11 \times 17 = 1683$$$, which ends with the digit 3. </p><p>In the fifth example, $$$2 \times 2 \times 2 \times 2 = 16$$$, which ends with the digit 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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:24:53</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c01598de3a71',t:'MTY5NjY2NzA5My40OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\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\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2100"]
1510E
1510
E
ru
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1e20b8e0e3763717d46bcf09c167c80e"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Приложения - 2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Приложения - 2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred) - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='1e20b8e0e3763717d46bcf09c167c80e'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showMessage("Не найдено условие задачи на вашем языке, однако вы можете скачать условия для всех задач соревнования в одном файле"); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%2Fattachments">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='1e20b8e0e3763717d46bcf09c167c80e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='1e20b8e0e3763717d46bcf09c167c80e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Условия <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <tr> <th>Название</th> <th>Язык</th> <th>Действия</th> </tr> <tr> <td> Statements (PDF) <div class="small notice" style="margin-top: 1em;"> Файл с условиями может содержать неактуальные ограничения по времени и памяти. Перейдите на страницу "Задачи" для просмотра актуальных ограничений. </div> </td> <td> английский </td> <td> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" target="_blank">Скачать</a> </td> </tr> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> <div style="display: none;"> <form id="deleteAttachmentForm" action=""><input type='hidden' name='csrf_token' value='1e20b8e0e3763717d46bcf09c167c80e'/> <input type="hidden" name="action" value="delete"/> <input type="hidden" name="contestId" value="1510"/> <input type="hidden" name="attachmentId" value=""/> </form> </div> <script type="text/javascript"> $(document).ready(function () { $("a.deleteAttachmentLink").click(function () { var attachmentRepresentation = $(this).attr("attachmentRepresentation"); var confirmationMessage = "Вы уверены, что хотите удалить \'%%attachmentRepresentation%%\'?" .replace("%%attachmentRepresentation%%", attachmentRepresentation); var attachmentId = $(this).attr("attachmentId"); Codeforces.confirm(confirmationMessage, function () { var deleteAttachmentForm = $("#deleteAttachmentForm"); deleteAttachmentForm.find("input[name=attachmentId]").val(attachmentId); deleteAttachmentForm.submit(); }, function () { }, "Да", "Нет" ); return false; }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:10</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0808dbe75af',t:'MTY5NjY2NzExMC41MzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
""
""
nan
1510F
1510
F
ru
F. Fiber Shape
<div class="problem-statement"><div class="header"><div class="title">F. Fiber Shape</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>Imagine a board with $$$n$$$ pins put into it, the $$$i$$$-th pin is located at $$$(x_i, y_i)$$$. For simplicity, we will restrict the problem to the case where the pins are placed in vertices of a convex polygon.</p><p>Then, take a non-stretchable string of length $$$l$$$, and put it around all the pins. Place a pencil inside the string and draw a curve around the pins, trying to pull the string in every possible direction. The picture below shows an example of a string tied around the pins and pulled by a pencil (a point $$$P$$$).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7fc6d0e632b37a9a0e664bd4411d3e2577e196e9.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Your task is to find an area inside this curve. Formally, for a given convex polygon $$$S$$$ and a length $$$l$$$ let's define a <span class="tex-font-style-underline">fiber shape</span> $$$F(S, l)$$$ as a set of points $$$t$$$ such that the perimeter of the convex hull of $$$S \cup \{t\}$$$ does not exceed $$$l$$$. Find an area of $$$F(S, l)$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains two integers $$$n$$$ and $$$l$$$ ($$$3 \le n \le 10^4$$$; $$$1 \le l \le 8 \cdot 10^5$$$) — the number of vertices of the polygon $$$S$$$ and the length of the string. Next $$$n$$$ lines contain integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^5 \le x_i, y_i \le 10^5$$$) — coordinates of polygon's vertices in counterclockwise order. All internal angles of the polygon are strictly less than $$$\pi$$$. The length $$$l$$$ exceeds the perimeter of the polygon by at least $$$10^{-3}$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output a single floating-point number — the area of the fiber shape $$$F(S, l)$$$. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. </p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 3 4 0 0 1 0 0 1 </pre></div><div class="output"><div class="title">Output</div><pre> 3.012712585980357 </pre></div><div class="input"><div class="title">Input</div><pre> 4 5 0 0 1 0 1 1 0 1 </pre></div><div class="output"><div class="title">Output</div><pre> 5.682061989789656 </pre></div><div class="input"><div class="title">Input</div><pre> 5 17 0 0 2 -1 3 0 4 3 -1 4 </pre></div><div class="output"><div class="title">Output</div><pre> 37.719371276930820 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>The following pictures illustrate the example tests.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/5469bab9183c8f183b71c44d0e8d2ec1350286b7.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img class="tex-graphics" src="https://espresso.codeforces.com/32fc31147283e2c9a4c83589f4e6f60537d4ff08.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a66153ed5e5212a0474bd62f15540d772e8db37b.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="0eb852a2a14c9dc032a443829393e1c5"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0eb852a2a14c9dc032a443829393e1c5'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%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='0eb852a2a14c9dc032a443829393e1c5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='0eb852a2a14c9dc032a443829393e1c5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound 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='0eb852a2a14c9dc032a443829393e1c5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946216"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0eb852a2a14c9dc032a443829393e1c5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946216"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_45adf7401432ab7d76e1c2fa43454a465630b8a3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Fiber Shape</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>Imagine a board with $$$n$$$ pins put into it, the $$$i$$$-th pin is located at $$$(x_i, y_i)$$$. For simplicity, we will restrict the problem to the case where the pins are placed in vertices of a convex polygon.</p><p>Then, take a non-stretchable string of length $$$l$$$, and put it around all the pins. Place a pencil inside the string and draw a curve around the pins, trying to pull the string in every possible direction. The picture below shows an example of a string tied around the pins and pulled by a pencil (a point $$$P$$$).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7fc6d0e632b37a9a0e664bd4411d3e2577e196e9.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Your task is to find an area inside this curve. Formally, for a given convex polygon $$$S$$$ and a length $$$l$$$ let's define a <span class="tex-font-style-underline">fiber shape</span> $$$F(S, l)$$$ as a set of points $$$t$$$ such that the perimeter of the convex hull of $$$S \cup \{t\}$$$ does not exceed $$$l$$$. Find an area of $$$F(S, l)$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains two integers $$$n$$$ and $$$l$$$ ($$$3 \le n \le 10^4$$$; $$$1 \le l \le 8 \cdot 10^5$$$) — the number of vertices of the polygon $$$S$$$ and the length of the string. Next $$$n$$$ lines contain integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^5 \le x_i, y_i \le 10^5$$$) — coordinates of polygon's vertices in counterclockwise order. All internal angles of the polygon are strictly less than $$$\pi$$$. The length $$$l$$$ exceeds the perimeter of the polygon by at least $$$10^{-3}$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output a single floating-point number — the area of the fiber shape $$$F(S, l)$$$. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. </p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 3 4 0 0 1 0 0 1 </pre></div><div class="output"><div class="title">Output</div><pre> 3.012712585980357 </pre></div><div class="input"><div class="title">Input</div><pre> 4 5 0 0 1 0 1 1 0 1 </pre></div><div class="output"><div class="title">Output</div><pre> 5.682061989789656 </pre></div><div class="input"><div class="title">Input</div><pre> 5 17 0 0 2 -1 3 0 4 3 -1 4 </pre></div><div class="output"><div class="title">Output</div><pre> 37.719371276930820 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>The following pictures illustrate the example tests.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/5469bab9183c8f183b71c44d0e8d2ec1350286b7.png" style="max-width: 100.0%;max-height: 100.0%;" /> <img class="tex-graphics" src="https://espresso.codeforces.com/32fc31147283e2c9a4c83589f4e6f60537d4ff08.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a66153ed5e5212a0474bd62f15540d772e8db37b.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:11</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0886e6c5aa6',t:'MTY5NjY2NzExMS44NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
["*2800"]
1510G
1510
G
ru
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="586b4ca439b0f81efdb9d830365a0385"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Приложения - 2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred) - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Приложения - 2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred) - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='586b4ca439b0f81efdb9d830365a0385'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showMessage("Не найдено условие задачи на вашем языке, однако вы можете скачать условия для всех задач соревнования в одном файле"); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%2Fattachments">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='586b4ca439b0f81efdb9d830365a0385'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='586b4ca439b0f81efdb9d830365a0385'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Условия <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <tr> <th>Название</th> <th>Язык</th> <th>Действия</th> </tr> <tr> <td> Statements (PDF) <div class="small notice" style="margin-top: 1em;"> Файл с условиями может содержать неактуальные ограничения по времени и памяти. Перейдите на страницу "Задачи" для просмотра актуальных ограничений. </div> </td> <td> английский </td> <td> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" target="_blank">Скачать</a> </td> </tr> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> <div style="display: none;"> <form id="deleteAttachmentForm" action=""><input type='hidden' name='csrf_token' value='586b4ca439b0f81efdb9d830365a0385'/> <input type="hidden" name="action" value="delete"/> <input type="hidden" name="contestId" value="1510"/> <input type="hidden" name="attachmentId" value=""/> </form> </div> <script type="text/javascript"> $(document).ready(function () { $("a.deleteAttachmentLink").click(function () { var attachmentRepresentation = $(this).attr("attachmentRepresentation"); var confirmationMessage = "Вы уверены, что хотите удалить \'%%attachmentRepresentation%%\'?" .replace("%%attachmentRepresentation%%", attachmentRepresentation); var attachmentId = $(this).attr("attachmentId"); Codeforces.confirm(confirmationMessage, function () { var deleteAttachmentForm = $("#deleteAttachmentForm"); deleteAttachmentForm.find("input[name=attachmentId]").val(attachmentId); deleteAttachmentForm.submit(); }, function () { }, "Да", "Нет" ); return false; }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:25</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0ddeab59db0',t:'MTY5NjY2NzEyNS40NzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
""
""
nan
1510H
1510
H
ru
H. Hard Optimization
<div class="problem-statement"><div class="header"><div class="title">H. Hard Optimization</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>You are given a set of $$$n$$$ segments on a line $$$[L_i; R_i]$$$. All $$$2n$$$ segment endpoints are pairwise distinct integers.</p><p>The set is <span class="tex-font-style-underline">laminar</span> — any two segments are either disjoint or one of them contains the other.</p><p>Choose a non-empty subsegment $$$[l_i, r_i]$$$ with integer endpoints in each segment ($$$L_i \le l_i &lt; r_i \le R_i$$$) in such a way that no two subsegments intersect (they are allowed to have common endpoints though) and the sum of their lengths ($$$\sum_{i=1}^n r_i - l_i$$$) is maximized.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^3$$$) — the number of segments.</p><p>The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$0 \le L_i &lt; R_i \le 10^9$$$) — the endpoints of the $$$i$$$-th segment.</p><p>All the given $$$2n$$$ segment endpoints are distinct. The set of segments is laminar.</p></div><div class="output-specification"><div class="section-title">Output</div><p>On the first line, output the maximum possible sum of subsegment lengths.</p><p>On the $$$i$$$-th of the next $$$n$$$ lines, output two integers $$$l_i$$$ and $$$r_i$$$ ($$$L_i \le l_i &lt; r_i \le R_i$$$), denoting the chosen subsegment of the $$$i$$$-th segment.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 4 1 10 2 3 5 9 6 7 </pre></div><div class="output"><div class="title">Output</div><pre> 7 3 6 2 3 7 9 6 7 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>The example input and the example output are illustrated below. <img class="tex-graphics" src="https://espresso.codeforces.com/777a7831426b9a3649b4272ba88d878492c03c8f.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img class="tex-graphics" src="https://espresso.codeforces.com/872f6adb4f7d0c9212c4372480f143e3b51a9342.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="18f315b5b61a66cc442bb5c1c081bc7a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='18f315b5b61a66cc442bb5c1c081bc7a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%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='18f315b5b61a66cc442bb5c1c081bc7a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='18f315b5b61a66cc442bb5c1c081bc7a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound 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='18f315b5b61a66cc442bb5c1c081bc7a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946218"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='18f315b5b61a66cc442bb5c1c081bc7a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946218"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8cedbddd1c600630b6225729610051b2534cc3cf"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">H. Hard Optimization</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>You are given a set of $$$n$$$ segments on a line $$$[L_i; R_i]$$$. All $$$2n$$$ segment endpoints are pairwise distinct integers.</p><p>The set is <span class="tex-font-style-underline">laminar</span> — any two segments are either disjoint or one of them contains the other.</p><p>Choose a non-empty subsegment $$$[l_i, r_i]$$$ with integer endpoints in each segment ($$$L_i \le l_i &lt; r_i \le R_i$$$) in such a way that no two subsegments intersect (they are allowed to have common endpoints though) and the sum of their lengths ($$$\sum_{i=1}^n r_i - l_i$$$) is maximized.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^3$$$) — the number of segments.</p><p>The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$0 \le L_i &lt; R_i \le 10^9$$$) — the endpoints of the $$$i$$$-th segment.</p><p>All the given $$$2n$$$ segment endpoints are distinct. The set of segments is laminar.</p></div><div class="output-specification"><div class="section-title">Output</div><p>On the first line, output the maximum possible sum of subsegment lengths.</p><p>On the $$$i$$$-th of the next $$$n$$$ lines, output two integers $$$l_i$$$ and $$$r_i$$$ ($$$L_i \le l_i &lt; r_i \le R_i$$$), denoting the chosen subsegment of the $$$i$$$-th segment.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 4 1 10 2 3 5 9 6 7 </pre></div><div class="output"><div class="title">Output</div><pre> 7 3 6 2 3 7 9 6 7 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>The example input and the example output are illustrated below. <img class="tex-graphics" src="https://espresso.codeforces.com/777a7831426b9a3649b4272ba88d878492c03c8f.png" style="max-width: 100.0%;max-height: 100.0%;" /> <img class="tex-graphics" src="https://espresso.codeforces.com/872f6adb4f7d0c9212c4372480f143e3b51a9342.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=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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:26</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0e5bcaa9d86',t:'MTY5NjY2NzEyNi43NzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "*3200"]
1510I
1510
I
ru
I. Is It Rated?
<div class="problem-statement"><div class="header"><div class="title">I. Is It Rated?</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>The popular improv website <span class="tex-font-style-underline">Interpretation Impetus</span> hosts regular improv contests and maintains a rating of the best performers. However, since improv can often go horribly wrong, the website is notorious for declaring improv contests <span class="tex-font-style-underline">unrated</span>. It now holds a wager before each improv contest where the participants try to predict whether it will be rated or unrated, and they are now more popular than the improv itself.</p><p>Izzy and $$$n$$$ other participants take part in each wager. First, they each make their prediction, expressed as <span class="tex-font-style-tt">1</span> ("rated") or <span class="tex-font-style-tt">0</span> ("unrated"). Izzy always goes last, so she knows the predictions of the other participants when making her own. Then, the actual competition takes place and it is declared either rated or unrated.</p><p>You need to write a program that will interactively play as Izzy. There will be $$$m$$$ wagers held in 2021, and Izzy's goal is to have at most $$$1.3\cdot b + 100$$$ wrong predictions after all those wagers, where $$$b$$$ is the <span class="tex-font-style-underline">smallest</span> number of wrong predictions that any other wager participant will have after all those wagers. </p><p>The number $$$b$$$ is not known in advance. Izzy also knows nothing about the other participants — they might somehow always guess correctly, or their predictions might be correlated. Izzy's predictions, though, do not affect the predictions of the other participants and the decision on the contest being rated or not — in other words, in each test case, your program always receives the same inputs, no matter what it outputs.</p></div><div><div class="section-title">Interaction</div><p>First, a solution must read two integers $$$n$$$ ($$$1 \le n \le 1000$$$) and $$$m$$$ ($$$1 \le m \le 10\,000$$$). Then, the solution must process $$$m$$$ wagers. For each of them, the solution must first read a string consisting of $$$n$$$ <span class="tex-font-style-tt">0</span>s and <span class="tex-font-style-tt">1</span>s, in which the $$$i$$$-th character denotes the guess of the $$$i$$$-th participant. Then, the solution must print Izzy's guess as <span class="tex-font-style-tt">0</span> or <span class="tex-font-style-tt">1</span>. Don't forget to flush the output after printing it! Then, the solution must read the actual outcome, also as <span class="tex-font-style-tt">0</span> or <span class="tex-font-style-tt">1</span>, and then proceed to the next wager, if this wasn't the last one. </p><p>Your solution will be considered correct if it makes at most $$$1.3\cdot b + 100$$$ mistakes, where $$$b$$$ is the smallest number of mistakes made by any other participant. Note that if a solution outputs anything except <span class="tex-font-style-tt">0</span> or <span class="tex-font-style-tt">1</span> for a wager, it will be considered incorrect even if it made no other mistakes. </p><p>There are 200 test cases in this problem.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 3 4 000 1 100 1 001 0 111 1 </pre></div><div class="output"><div class="title">Output</div><pre> 0 0 1 1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the example, the participants made 1, 2, and 3 mistakes respectively, therefore $$$b=1$$$ (the smallest of these numbers). Izzy made 3 mistakes, which were not more than $$$1.3\cdot b + 100=101.3$$$, so these outputs are good enough to pass this test case (as are any other valid outputs).</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="d563ded4543e57e9a3f75271e6448715"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - I - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - I - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d563ded4543e57e9a3f75271e6448715'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%2Fproblem%2FI%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='d563ded4543e57e9a3f75271e6448715'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='d563ded4543e57e9a3f75271e6448715'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound 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='d563ded4543e57e9a3f75271e6448715'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946219"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d563ded4543e57e9a3f75271e6448715'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946219"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="I" data-uuid="ps_cee6bcfdbb624f308fbaace12b07b84b0583983f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">I. Is It Rated?</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>The popular improv website <span class="tex-font-style-underline">Interpretation Impetus</span> hosts regular improv contests and maintains a rating of the best performers. However, since improv can often go horribly wrong, the website is notorious for declaring improv contests <span class="tex-font-style-underline">unrated</span>. It now holds a wager before each improv contest where the participants try to predict whether it will be rated or unrated, and they are now more popular than the improv itself.</p><p>Izzy and $$$n$$$ other participants take part in each wager. First, they each make their prediction, expressed as <span class="tex-font-style-tt">1</span> (&quot;rated&quot;) or <span class="tex-font-style-tt">0</span> (&quot;unrated&quot;). Izzy always goes last, so she knows the predictions of the other participants when making her own. Then, the actual competition takes place and it is declared either rated or unrated.</p><p>You need to write a program that will interactively play as Izzy. There will be $$$m$$$ wagers held in 2021, and Izzy's goal is to have at most $$$1.3\cdot b + 100$$$ wrong predictions after all those wagers, where $$$b$$$ is the <span class="tex-font-style-underline">smallest</span> number of wrong predictions that any other wager participant will have after all those wagers. </p><p>The number $$$b$$$ is not known in advance. Izzy also knows nothing about the other participants — they might somehow always guess correctly, or their predictions might be correlated. Izzy's predictions, though, do not affect the predictions of the other participants and the decision on the contest being rated or not — in other words, in each test case, your program always receives the same inputs, no matter what it outputs.</p></div><div><div class="section-title">Interaction</div><p>First, a solution must read two integers $$$n$$$ ($$$1 \le n \le 1000$$$) and $$$m$$$ ($$$1 \le m \le 10\,000$$$). Then, the solution must process $$$m$$$ wagers. For each of them, the solution must first read a string consisting of $$$n$$$ <span class="tex-font-style-tt">0</span>s and <span class="tex-font-style-tt">1</span>s, in which the $$$i$$$-th character denotes the guess of the $$$i$$$-th participant. Then, the solution must print Izzy's guess as <span class="tex-font-style-tt">0</span> or <span class="tex-font-style-tt">1</span>. Don't forget to flush the output after printing it! Then, the solution must read the actual outcome, also as <span class="tex-font-style-tt">0</span> or <span class="tex-font-style-tt">1</span>, and then proceed to the next wager, if this wasn't the last one. </p><p>Your solution will be considered correct if it makes at most $$$1.3\cdot b + 100$$$ mistakes, where $$$b$$$ is the smallest number of mistakes made by any other participant. Note that if a solution outputs anything except <span class="tex-font-style-tt">0</span> or <span class="tex-font-style-tt">1</span> for a wager, it will be considered incorrect even if it made no other mistakes. </p><p>There are 200 test cases in this problem.</p></div><div class="sample-tests"><div class="section-title">Example</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 3 4 000 1 100 1 001 0 111 1 </pre></div><div class="output"><div class="title">Output</div><pre> 0 0 1 1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the example, the participants made 1, 2, and 3 mistakes respectively, therefore $$$b=1$$$ (the smallest of these numbers). Izzy made 3 mistakes, which were not more than $$$1.3\cdot b + 100=101.3$$$, so these outputs are good enough to pass this test case (as are any other valid outputs).</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=I]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:28</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0ee98677b8b',t:'MTY5NjY2NzEyOC4yMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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.", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*2700"]
1510J
1510
J
ru
J. Japanese Game
<div class="problem-statement"><div class="header"><div class="title">J. Japanese Game</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>Joseph really likes the culture of Japan. Last year he learned Japanese traditional clothes and visual arts and now he is trying to find out the secret of the Japanese game called Nonogram.</p><p>In the one-dimensional version of the game, there is a row of $$$n$$$ empty cells, some of which are to be filled with a pen. There is a description of a solution called a <span class="tex-font-style-underline">profile</span> — a sequence of positive integers denoting the lengths of consecutive sets of filled cells. For example, the profile of $$$[4, 3, 1]$$$ means that there are sets of four, three, and one filled cell, in that order, with at least one empty cell between successive sets.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7a2ec6eef2a8990ca87369275e00ff3d727142b6.png" style="max-width: 100.0%;max-height: 100.0%;"/><p>A suitable solution for $$$n = 12$$$ and $$$p = [4, 3, 1]$$$. </p></center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/576966c8c448e6c57711c7c8c48b57ee891143df.png" style="max-width: 100.0%;max-height: 100.0%;"/><p>A wrong solution: the first four filled cells should be consecutive. </p></center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fcabfef8f4c2e5ea68b94a6ec84ba5d3930b38f0.png" style="max-width: 100.0%;max-height: 100.0%;"/><p>A wrong solution: there should be at least one empty cell before the last filled cell. </p></center><p>Joseph found out that for some numbers $$$n$$$ and profiles $$$p$$$ there are lots of ways to fill the cells to satisfy the profile. Now he is in the process of solving a nonogram consisting of $$$n$$$ cells and a profile $$$p$$$. He has already created a <span class="tex-font-style-underline">mask</span> of $$$p$$$ — he has filled all the cells that must be filled in every solution of the nonogram.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e9defc82c67384b93c6d14f4cc99554ea8f3adf6.png" style="max-width: 100.0%;max-height: 100.0%;"/><p>The mask for $$$n = 12$$$ and $$$p = [4, 3, 1]$$$: all the filled cells above are filled in every solution. </p></center><p>After a break, he lost the source profile $$$p$$$. He only has $$$n$$$ and the mask $$$m$$$. Help Joseph find any profile $$$p'$$$ with the mask $$$m$$$ or say that there is no such profile and Joseph has made a mistake.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The only line contains a string $$$m$$$ — the mask of the source profile $$$p$$$. The length of $$$m$$$ is $$$n$$$ ($$$1 \le n \le 100\,000$$$). The string $$$m$$$ consists of symbols <span class="tex-font-style-tt">#</span> and <span class="tex-font-style-tt">_</span> — denoting filled and empty cells respectively.</p></div><div class="output-specification"><div class="section-title">Output</div><p>If there is no profile with the mask $$$m$$$, output the number $$$-1$$$. Otherwise, on the first line, output an integer $$$k$$$ — the number of integers in the profile $$$p'$$$. On the second line, output $$$k$$$ integers of the profile $$$p'$$$.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> __#_____ </pre></div><div class="output"><div class="title">Output</div><pre> 2 3 2 </pre></div><div class="input"><div class="title">Input</div><pre> _# </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> ___ </pre></div><div class="output"><div class="title">Output</div><pre> 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4336a097237a96888c1d6eb15a1c946b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - J - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - J - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='4336a097237a96888c1d6eb15a1c946b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%2Fproblem%2FJ%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='4336a097237a96888c1d6eb15a1c946b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='4336a097237a96888c1d6eb15a1c946b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='4336a097237a96888c1d6eb15a1c946b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946220"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4336a097237a96888c1d6eb15a1c946b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946220"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="J" data-uuid="ps_9e9bc416b16da5f00a84e6428e3536207e866f37"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">J. Japanese Game</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>Joseph really likes the culture of Japan. Last year he learned Japanese traditional clothes and visual arts and now he is trying to find out the secret of the Japanese game called Nonogram.</p><p>In the one-dimensional version of the game, there is a row of $$$n$$$ empty cells, some of which are to be filled with a pen. There is a description of a solution called a <span class="tex-font-style-underline">profile</span> — a sequence of positive integers denoting the lengths of consecutive sets of filled cells. For example, the profile of $$$[4, 3, 1]$$$ means that there are sets of four, three, and one filled cell, in that order, with at least one empty cell between successive sets.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7a2ec6eef2a8990ca87369275e00ff3d727142b6.png" style="max-width: 100.0%;max-height: 100.0%;" /><p>A suitable solution for $$$n = 12$$$ and $$$p = [4, 3, 1]$$$. </p></center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/576966c8c448e6c57711c7c8c48b57ee891143df.png" style="max-width: 100.0%;max-height: 100.0%;" /><p>A wrong solution: the first four filled cells should be consecutive. </p></center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fcabfef8f4c2e5ea68b94a6ec84ba5d3930b38f0.png" style="max-width: 100.0%;max-height: 100.0%;" /><p>A wrong solution: there should be at least one empty cell before the last filled cell. </p></center><p>Joseph found out that for some numbers $$$n$$$ and profiles $$$p$$$ there are lots of ways to fill the cells to satisfy the profile. Now he is in the process of solving a nonogram consisting of $$$n$$$ cells and a profile $$$p$$$. He has already created a <span class="tex-font-style-underline">mask</span> of $$$p$$$ — he has filled all the cells that must be filled in every solution of the nonogram.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e9defc82c67384b93c6d14f4cc99554ea8f3adf6.png" style="max-width: 100.0%;max-height: 100.0%;" /><p>The mask for $$$n = 12$$$ and $$$p = [4, 3, 1]$$$: all the filled cells above are filled in every solution. </p></center><p>After a break, he lost the source profile $$$p$$$. He only has $$$n$$$ and the mask $$$m$$$. Help Joseph find any profile $$$p'$$$ with the mask $$$m$$$ or say that there is no such profile and Joseph has made a mistake.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The only line contains a string $$$m$$$ — the mask of the source profile $$$p$$$. The length of $$$m$$$ is $$$n$$$ ($$$1 \le n \le 100\,000$$$). The string $$$m$$$ consists of symbols <span class="tex-font-style-tt">#</span> and <span class="tex-font-style-tt">_</span> — denoting filled and empty cells respectively.</p></div><div class="output-specification"><div class="section-title">Output</div><p>If there is no profile with the mask $$$m$$$, output the number $$$-1$$$. Otherwise, on the first line, output an integer $$$k$$$ — the number of integers in the profile $$$p'$$$. On the second line, output $$$k$$$ integers of the profile $$$p'$$$.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> __#_____ </pre></div><div class="output"><div class="title">Output</div><pre> 2 3 2 </pre></div><div class="input"><div class="title">Input</div><pre> _# </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> ___ </pre></div><div class="output"><div class="title">Output</div><pre> 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=J]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:29</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0f739269d8d',t:'MTY5NjY2NzEyOS42MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2700"]
1510K
1510
K
ru
K. King's Task
<div class="problem-statement"><div class="header"><div class="title">K. King's Task</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.</p><p>There is a permutation $$$p_i$$$ of numbers from 1 to $$$2n$$$. You can make two types of operations. </p><ol> <li> Swap $$$p_1$$$ and $$$p_2$$$, $$$p_3$$$ and $$$p_4$$$, ..., $$$p_{2n-1}$$$ and $$$p_{2n}$$$. </li><li> Swap $$$p_1$$$ and $$$p_{n+1}$$$, $$$p_2$$$ and $$$p_{n+2}$$$, ..., $$$p_{n}$$$ and $$$p_{2n}$$$. </li></ol><p>The task is to find the minimal number of operations required to sort the given permutation.</p><p>The Knight was not that smart actually, but quite charming, so the princess asks you to help him to solve the King's task.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains the integer $$$n$$$ ($$$1\le n\le 1000$$$). The second line contains $$$2n$$$ integers $$$p_i$$$ — the permutation of numbers from 1 to $$$2n$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print one integer — the minimal number of operations required to sort the permutation. If it is impossible to sort the permutation using these operations, print $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 3 6 3 2 5 4 1 </pre></div><div class="output"><div class="title">Output</div><pre> 3 </pre></div><div class="input"><div class="title">Input</div><pre> 2 3 4 2 1 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 4 1 2 3 4 5 6 7 8 </pre></div><div class="output"><div class="title">Output</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first example, you can sort the permutation in three operations: </p><ol> <li> Make operation 1: $$$3, 6, 5, 2, 1, 4$$$. </li><li> Make operation 2: $$$2, 1, 4, 3, 6, 5$$$. </li><li> Make operation 1: $$$1, 2, 3, 4, 5, 6$$$. </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2dda4046d8a350ce01bfddd8ee031da6"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <meta property="og:title" content="Задача - K - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="0baa0d9ae6afa3cad456b04aa3b41a35cfc84a15"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - K - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2dda4046d8a350ce01bfddd8ee031da6'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1510%2Fproblem%2FK%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='2dda4046d8a350ce01bfddd8ee031da6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1510">2020-2021 ICPC, NERC, Northern Eurasia Onsite (Unrated, Online Mirror, ICPC Rules, Teams Preferred)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2dda4046d8a350ce01bfddd8ee031da6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1510/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='2dda4046d8a350ce01bfddd8ee031da6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="946221"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2dda4046d8a350ce01bfddd8ee031da6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="946221"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89224" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13487" resourceName="A" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//assets.codeforces.com/rounds/1510/statements-1510.pdf" title="Statements (PDF)" target="_blank">Statements (PDF) <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13438" resourceName="Statements (PDF)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="//neerc.ifmo.ru/archive/2020/nerc-2020-offline-tutorial.pdf" title="nerc-2020-offline-tutorial.pdf" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13470" resourceName="nerc-2020-offline-tutorial.pdf" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1510">Задачи</a></li> <li><a href="/contest/1510/submit">Отослать</a></li> <li><a href="/contest/1510/my">Мои посылки</a></li> <li><a href="/contest/1510/status">Статус</a></li> <li><a href="/contest/1510/standings">Положение</a></li> <li><a href="/contest/1510/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="K" data-uuid="ps_920226c459d36e8b4dbfb4e0edb1296b1e85a38d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">K. King's Task</div><div class="time-limit"><div class="property-title">time limit per test</div>3 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>512 megabytes</div><div class="input-file"><div class="property-title">input</div>standard input</div><div class="output-file"><div class="property-title">output</div>standard output</div></div><div><p>The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.</p><p>There is a permutation $$$p_i$$$ of numbers from 1 to $$$2n$$$. You can make two types of operations. </p><ol> <li> Swap $$$p_1$$$ and $$$p_2$$$, $$$p_3$$$ and $$$p_4$$$, ..., $$$p_{2n-1}$$$ and $$$p_{2n}$$$. </li><li> Swap $$$p_1$$$ and $$$p_{n+1}$$$, $$$p_2$$$ and $$$p_{n+2}$$$, ..., $$$p_{n}$$$ and $$$p_{2n}$$$. </li></ol><p>The task is to find the minimal number of operations required to sort the given permutation.</p><p>The Knight was not that smart actually, but quite charming, so the princess asks you to help him to solve the King's task.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains the integer $$$n$$$ ($$$1\le n\le 1000$$$). The second line contains $$$2n$$$ integers $$$p_i$$$ — the permutation of numbers from 1 to $$$2n$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print one integer — the minimal number of operations required to sort the permutation. If it is impossible to sort the permutation using these operations, print $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Examples</div><div class="sample-test"><div class="input"><div class="title">Input</div><pre> 3 6 3 2 5 4 1 </pre></div><div class="output"><div class="title">Output</div><pre> 3 </pre></div><div class="input"><div class="title">Input</div><pre> 2 3 4 2 1 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 4 1 2 3 4 5 6 7 8 </pre></div><div class="output"><div class="title">Output</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first example, you can sort the permutation in three operations: </p><ol> <li> Make operation 1: $$$3, 6, 5, 2, 1, 4$$$. </li><li> Make operation 2: $$$2, 1, 4, 3, 6, 5$$$. </li><li> Make operation 1: $$$1, 2, 3, 4, 5, 6$$$. </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=K]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:30</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c0ffabf616fe',t:'MTY5NjY2NzEzMC45NTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"]
1511A
1511
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>Однако сайт не так прост внутри. Есть два сервера, на каждом из них лайки и дизлайки считаются независимо.</p><p>$$$n$$$ пользователей заходят на сайт один за другим. Каждый пользователь одного из следующих типов: </p><ul> <li> тип $$$1$$$: пользователь смотрел фильм, и он им понравился — они нажимают лайк; </li><li> тип $$$2$$$: пользователь смотрел фильм, и он им не понравился — они нажимают дизлайк; </li><li> тип $$$3$$$: пользователь не смотрел фильм — они смотрят на текущее количество лайков и дизлайков и решают на какую кнопку нажимать. Если больше дизлайков, чем лайков, то пользователь ставит дизлайк. Иначе, они ставят лайк. </li></ul><p>Каждый пользователь оценивает фильм ровно один раз.</p><p>Так как у вас есть два сервера, можно манипулировать оценками, чтобы фильм получил как можно больше лайков. Когда пользователь заходит на сайт, вы знаете его тип, и можете решить, на какой из двух серверов его послать.</p><p>Какое наибольшее количество лайков можно собрать в сумме по двум серверам, если распределить пользователей по двум серверам?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Затем следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — количество пользователей.</p><p>Во второй строке каждого набора входных данных записано $$$n$$$ целых чисел $$$r_1, r_2, \dots, r_n$$$ ($$$1 \le r_i \le 3$$$) — типы пользователей в том же порядке, в котором они заходят на сайт.</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 2 3 1 2 3 5 1 1 1 1 1 3 3 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 5 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных в примере можно послать единственного пользователя на любой сервер — они все равно поставят дизлайк. Фильм не получит лайков.</p><p>Во втором наборе входных данных в примере можно послать всех пользователей на первый сервер: </p><ul> <li> первый пользователь ставит лайк; </li><li> второй пользователь ставит дизлайк; </li><li> последний пользователь видит, что количество дизлайков не превышает количество лайков — ставит лайк сам. </li></ul><p>Всего в сумме два лайка. Вместо этого можно послать первого и второго пользователя на первый сервер, а последнего — на второй. </p><ul> <li> первый пользователь ставит лайк на первом сервере; </li><li> второй пользователь ставит дизлайк на первом сервере; </li><li> последний пользователь не видит лайков или дизлайков на втором сервере — ставит лайк сам. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a5103e8d5009e3d410e4766831e02918"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a5103e8d5009e3d410e4766831e02918'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='a5103e8d5009e3d410e4766831e02918'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a5103e8d5009e3d410e4766831e02918'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound 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='a5103e8d5009e3d410e4766831e02918'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955212"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a5103e8d5009e3d410e4766831e02918'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955212"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c3cf10f8f2aad57d2f7336308ab330ba2799a5d5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Однако сайт не так прост внутри. Есть два сервера, на каждом из них лайки и дизлайки считаются независимо.</p><p>$$$n$$$ пользователей заходят на сайт один за другим. Каждый пользователь одного из следующих типов: </p><ul> <li> тип $$$1$$$: пользователь смотрел фильм, и он им понравился — они нажимают лайк; </li><li> тип $$$2$$$: пользователь смотрел фильм, и он им не понравился — они нажимают дизлайк; </li><li> тип $$$3$$$: пользователь не смотрел фильм — они смотрят на текущее количество лайков и дизлайков и решают на какую кнопку нажимать. Если больше дизлайков, чем лайков, то пользователь ставит дизлайк. Иначе, они ставят лайк. </li></ul><p>Каждый пользователь оценивает фильм ровно один раз.</p><p>Так как у вас есть два сервера, можно манипулировать оценками, чтобы фильм получил как можно больше лайков. Когда пользователь заходит на сайт, вы знаете его тип, и можете решить, на какой из двух серверов его послать.</p><p>Какое наибольшее количество лайков можно собрать в сумме по двум серверам, если распределить пользователей по двум серверам?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Затем следуют описания $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — количество пользователей.</p><p>Во второй строке каждого набора входных данных записано $$$n$$$ целых чисел $$$r_1, r_2, \dots, r_n$$$ ($$$1 \le r_i \le 3$$$) — типы пользователей в том же порядке, в котором они заходят на сайт.</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 2 3 1 2 3 5 1 1 1 1 1 3 3 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 2 5 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных в примере можно послать единственного пользователя на любой сервер — они все равно поставят дизлайк. Фильм не получит лайков.</p><p>Во втором наборе входных данных в примере можно послать всех пользователей на первый сервер: </p><ul> <li> первый пользователь ставит лайк; </li><li> второй пользователь ставит дизлайк; </li><li> последний пользователь видит, что количество дизлайков не превышает количество лайков — ставит лайк сам. </li></ul><p>Всего в сумме два лайка. Вместо этого можно послать первого и второго пользователя на первый сервер, а последнего — на второй. </p><ul> <li> первый пользователь ставит лайк на первом сервере; </li><li> второй пользователь ставит дизлайк на первом сервере; </li><li> последний пользователь не видит лайков или дизлайков на втором сервере — ставит лайк сам. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:32</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c108e90716e8',t:'MTY5NjY2NzEzMi41MTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*800"]
1511B
1511
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$$$, $$$b$$$ и $$$c$$$.</p><p>Найдите два целых положительных числа $$$x$$$ и $$$y$$$ ($$$x &gt; 0$$$, $$$y &gt; 0$$$) такие, что: </p><ul> <li> десятичная запись $$$x$$$ без лидирующих нулей состоит из $$$a$$$ цифр; </li><li> десятичная запись $$$y$$$ без лидирующих нулей состоит из $$$b$$$ цифр; </li><li> десятичная запись $$$gcd(x, y)$$$ без лидирующих нулей состоит из $$$c$$$ цифр. </li></ul><p>$$$gcd(x, y)$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольший общий делитель (НОД)</a> чисел $$$x$$$ и $$$y$$$.</p><p>Выведите $$$x$$$ и $$$y$$$. Если возможны несколько ответов, то выведите любой из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 285$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$t$$$ строк записаны по три целых числа $$$a$$$, $$$b$$$ и $$$c$$$ ($$$1 \le a, b \le 9$$$, $$$1 \le c \le min(a, b)$$$) — необходимые длины чисел.</p><p>Можно показать, что ответ существует для всех наборов входных данных при заданных ограничениях.</p><p>Дополнительное ограничение на входные данные: все наборы входных данных различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите два целых положительных числа — $$$x$$$ и $$$y$$$ ($$$x &gt; 0$$$, $$$y &gt; 0$$$) такие, что: </p><ul> <li> десятичная запись $$$x$$$ без лидирующих нулей состоит из $$$a$$$ цифр; </li><li> десятичная запись $$$y$$$ без лидирующих нулей состоит из $$$b$$$ цифр; </li><li> десятичная запись $$$gcd(x, y)$$$ без лидирующих нулей состоит из $$$c$$$ цифр. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 3 1 2 2 2 6 6 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 492 13 26 140133 160776 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере: </p><ol> <li> $$$gcd(11, 492) = 1$$$ </li><li> $$$gcd(13, 26) = 13$$$ </li><li> $$$gcd(140133, 160776) = 21$$$ </li><li> $$$gcd(1, 1) = 1$$$ </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="369e8ee00f20ed16da23bb5449506e18"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='369e8ee00f20ed16da23bb5449506e18'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='369e8ee00f20ed16da23bb5449506e18'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='369e8ee00f20ed16da23bb5449506e18'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='369e8ee00f20ed16da23bb5449506e18'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955213"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='369e8ee00f20ed16da23bb5449506e18'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955213"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1938d9c936a56c9b24788f4963bd923266db61d8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$, $$$b$$$ и $$$c$$$.</p><p>Найдите два целых положительных числа $$$x$$$ и $$$y$$$ ($$$x &gt; 0$$$, $$$y &gt; 0$$$) такие, что: </p><ul> <li> десятичная запись $$$x$$$ без лидирующих нулей состоит из $$$a$$$ цифр; </li><li> десятичная запись $$$y$$$ без лидирующих нулей состоит из $$$b$$$ цифр; </li><li> десятичная запись $$$gcd(x, y)$$$ без лидирующих нулей состоит из $$$c$$$ цифр. </li></ul><p>$$$gcd(x, y)$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольший общий делитель (НОД)</a> чисел $$$x$$$ и $$$y$$$.</p><p>Выведите $$$x$$$ и $$$y$$$. Если возможны несколько ответов, то выведите любой из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 285$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$t$$$ строк записаны по три целых числа $$$a$$$, $$$b$$$ и $$$c$$$ ($$$1 \le a, b \le 9$$$, $$$1 \le c \le min(a, b)$$$) — необходимые длины чисел.</p><p>Можно показать, что ответ существует для всех наборов входных данных при заданных ограничениях.</p><p>Дополнительное ограничение на входные данные: все наборы входных данных различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите два целых положительных числа — $$$x$$$ и $$$y$$$ ($$$x &gt; 0$$$, $$$y &gt; 0$$$) такие, что: </p><ul> <li> десятичная запись $$$x$$$ без лидирующих нулей состоит из $$$a$$$ цифр; </li><li> десятичная запись $$$y$$$ без лидирующих нулей состоит из $$$b$$$ цифр; </li><li> десятичная запись $$$gcd(x, y)$$$ без лидирующих нулей состоит из $$$c$$$ цифр. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 3 1 2 2 2 6 6 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 492 13 26 140133 160776 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере: </p><ol> <li> $$$gcd(11, 492) = 1$$$ </li><li> $$$gcd(13, 26) = 13$$$ </li><li> $$$gcd(140133, 160776) = 21$$$ </li><li> $$$gcd(1, 1) = 1$$$ </li></ol></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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:33</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c111c9b416ab',t:'MTY5NjY2NzEzMy44MjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1511C
1511
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$$$. У каждой карты есть цвет: цвет $$$i$$$-й карты равен $$$a_i$$$.</p><p>Вам нужно обработать $$$q$$$ запросов: $$$j$$$-й запрос описывается одним целым числом $$$t_j$$$. Для каждого запроса вам нужно: </p><ul> <li> найти самую верхнюю карту в колоде с цветом $$$t_j$$$, т. е. карту с минимальным индексом; </li><li> вывести индекс найденной карты; </li><li> вытащить данную карту и положить ее сверху колоды. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$q$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$1 \le q \le 3 \cdot 10^5$$$) — количество карт в колоде и количество запросов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — цвета карт.</p><p>В третьей строке заданы $$$q$$$ целых чисел $$$t_1, t_2, \dots, t_q$$$ ($$$1 \le t_j \le 50$$$) — цвета в запросах. Гарантируется, что <span class="tex-font-style-bf">в запросах используются только цвета, представленные в колоде</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел — ответы на все запросы.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 5 2 1 1 4 3 3 1 3 2 1 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 2 3 1 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Описание примера: </p><ol> <li> текущая колода $$$[2, 1, 1, 4, \underline{3}, 3, 1]$$$ и верхняя карта цвета $$$t_1 = 3$$$ на позиции $$$5$$$; </li><li> текущая колода $$$[3, \underline{2}, 1, 1, 4, 3, 1]$$$ и верхняя карта цвета $$$t_2 = 2$$$ на позиции $$$2$$$; </li><li> текущая колода $$$[2, 3, \underline{1}, 1, 4, 3, 1]$$$ и верхняя карта цвета $$$t_3 = 1$$$ на позиции $$$3$$$; </li><li> текущая колода $$$[\underline{1}, 2, 3, 1, 4, 3, 1]$$$ и верхняя карта цвета $$$t_4 = 1$$$ на позиции $$$1$$$; </li><li> текущая колода $$$[1, 2, 3, 1, \underline{4}, 3, 1]$$$ и верхняя карта цвета $$$t_5 = 4$$$ на позиции $$$5$$$. </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d9e03dd1c5add746642d141153ece37b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='d9e03dd1c5add746642d141153ece37b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='d9e03dd1c5add746642d141153ece37b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='d9e03dd1c5add746642d141153ece37b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='d9e03dd1c5add746642d141153ece37b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955214"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d9e03dd1c5add746642d141153ece37b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955214"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_80fb3955e06cb398a5b5d70f9183f93f571907ff"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$. У каждой карты есть цвет: цвет $$$i$$$-й карты равен $$$a_i$$$.</p><p>Вам нужно обработать $$$q$$$ запросов: $$$j$$$-й запрос описывается одним целым числом $$$t_j$$$. Для каждого запроса вам нужно: </p><ul> <li> найти самую верхнюю карту в колоде с цветом $$$t_j$$$, т. е. карту с минимальным индексом; </li><li> вывести индекс найденной карты; </li><li> вытащить данную карту и положить ее сверху колоды. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$q$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$1 \le q \le 3 \cdot 10^5$$$) — количество карт в колоде и количество запросов.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — цвета карт.</p><p>В третьей строке заданы $$$q$$$ целых чисел $$$t_1, t_2, \dots, t_q$$$ ($$$1 \le t_j \le 50$$$) — цвета в запросах. Гарантируется, что <span class="tex-font-style-bf">в запросах используются только цвета, представленные в колоде</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел — ответы на все запросы.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 5 2 1 1 4 3 3 1 3 2 1 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 2 3 1 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Описание примера: </p><ol> <li> текущая колода $$$[2, 1, 1, 4, \underline{3}, 3, 1]$$$ и верхняя карта цвета $$$t_1 = 3$$$ на позиции $$$5$$$; </li><li> текущая колода $$$[3, \underline{2}, 1, 1, 4, 3, 1]$$$ и верхняя карта цвета $$$t_2 = 2$$$ на позиции $$$2$$$; </li><li> текущая колода $$$[2, 3, \underline{1}, 1, 4, 3, 1]$$$ и верхняя карта цвета $$$t_3 = 1$$$ на позиции $$$3$$$; </li><li> текущая колода $$$[\underline{1}, 2, 3, 1, 4, 3, 1]$$$ и верхняя карта цвета $$$t_4 = 1$$$ на позиции $$$1$$$; </li><li> текущая колода $$$[1, 2, 3, 1, \underline{4}, 3, 1]$$$ и верхняя карта цвета $$$t_5 = 4$$$ на позиции $$$5$$$. </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:35</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c11a283a7a75',t:'MTY5NjY2NzEzNS4yMTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1100"]
1511D
1511
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">стоимость</span> строки $$$s$$$ как количество пар индексов $$$i$$$ и $$$j$$$ ($$$1 \le i &lt; j &lt; |s|$$$) таких, что $$$s_i = s_j$$$ и $$$s_{i+1} = s_{j+1}$$$.</p><p>Заданы два положительных целых числа $$$n$$$ и $$$k$$$. Среди всех строк длины $$$n$$$, содержащих только первые $$$k$$$ букв латинского алфавита, найдите строку с минимально возможной <span class="tex-font-style-it">стоимостью</span>. Если таких строк несколько — найдите любую из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 26$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку $$$s$$$ такую, что она состоит из $$$n$$$ символов, каждый из которых является одной из первых $$$k$$$ латинских букв, и она имеет минимально возможную <span class="tex-font-style-it">стоимость</span> среди всех таких строк. Если таких строк несколько — выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 9 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aabacadbb </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaaaa</pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 26 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> codeforces </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="fff5de8f427eec545105bc962f89b51d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='fff5de8f427eec545105bc962f89b51d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='fff5de8f427eec545105bc962f89b51d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='fff5de8f427eec545105bc962f89b51d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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="Сложность"> *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='fff5de8f427eec545105bc962f89b51d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955215"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fff5de8f427eec545105bc962f89b51d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955215"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6e397bfd14fda70d49f1762c8ddff96e435e0bd9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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">стоимость</span> строки $$$s$$$ как количество пар индексов $$$i$$$ и $$$j$$$ ($$$1 \le i &lt; j &lt; |s|$$$) таких, что $$$s_i = s_j$$$ и $$$s_{i+1} = s_{j+1}$$$.</p><p>Заданы два положительных целых числа $$$n$$$ и $$$k$$$. Среди всех строк длины $$$n$$$, содержащих только первые $$$k$$$ букв латинского алфавита, найдите строку с минимально возможной <span class="tex-font-style-it">стоимостью</span>. Если таких строк несколько — найдите любую из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 26$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку $$$s$$$ такую, что она состоит из $$$n$$$ символов, каждый из которых является одной из первых $$$k$$$ латинских букв, и она имеет минимально возможную <span class="tex-font-style-it">стоимость</span> среди всех таких строк. Если таких строк несколько — выведите любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 9 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aabacadbb </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaaaa</pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 26 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> codeforces </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:36</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c122be6d164b',t:'MTY5NjY2NzEzNi41OTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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"]
["\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1600"]
1511E
1511
E
ru
E. Раскраски и домино
<div class="problem-statement"><div class="header"><div class="title">E. Раскраски и домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть большая прямоугольная доска, разделенная на $$$n \times m$$$ клетка (у доски $$$n$$$ строк и $$$m$$$ столбцов). Каждая клетка — либо белая, либо черная.</p><p>Вы красите каждую белую клетку либо в красный цвет, либо в синий. Очевидно, количество различных вариантов раскраски доски равно $$$2^w$$$, где $$$w$$$ — количество белых клеток.</p><p>После перекрашивания всех белых клеток вы начинаете класть на доску доминошки по следующим правилам:</p><ul> <li> каждая доминошка накрывает две соседние клетки; </li><li> каждая клетка накрыта не более чем одной доминошкой; </li><li> если доминошка расположена горизонтально (она накрывает две соседние клетки в строке), обе накрытые ею клетки должны быть красными; </li><li> если доминошка расположена вертикально (она накрывает две соседние клетки в столбце), обе накрытые ею клетки должны быть синими. </li></ul><p>Пусть <span class="tex-font-style-it">ценность</span> раскраски доски — максимальное количество доминошек, которое можно расположить. Посчитайте сумму <span class="tex-font-style-it">ценностей</span> по всем $$$2^w$$$ способам раскрасить доску. Так как сумма может быть очень большой, выведите ее по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 3 \cdot 10^5$$$; $$$nm \le 3 \cdot 10^5$$$) — количество строк и столбцов, соответственно.</p><p>Затем следуют $$$n$$$ строк, в каждой из которых задана последовательность из $$$m$$$ символов. Символ под номером $$$j$$$ в $$$i$$$-й последовательности — <span class="tex-font-style-tt">*</span>, если $$$j$$$-я клетка $$$i$$$-й строки черная; иначе этот символ — <span class="tex-font-style-tt">o</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — сумму <span class="tex-font-style-it">ценностей</span> по всем $$$2^w$$$ способам раскрасить доску, взятую по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 **oo oo*o **oo </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 144 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 **oo oo** **oo </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 48 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 oo o* </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 4 oooo </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 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="111d0e0b91992107398e04c518bec67b"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='111d0e0b91992107398e04c518bec67b'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='111d0e0b91992107398e04c518bec67b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='111d0e0b91992107398e04c518bec67b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='111d0e0b91992107398e04c518bec67b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955216"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='111d0e0b91992107398e04c518bec67b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955216"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f5ea52104f3b3752e8d8a17ebf76c548a4046515"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Раскраски и домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть большая прямоугольная доска, разделенная на $$$n \times m$$$ клетка (у доски $$$n$$$ строк и $$$m$$$ столбцов). Каждая клетка — либо белая, либо черная.</p><p>Вы красите каждую белую клетку либо в красный цвет, либо в синий. Очевидно, количество различных вариантов раскраски доски равно $$$2^w$$$, где $$$w$$$ — количество белых клеток.</p><p>После перекрашивания всех белых клеток вы начинаете класть на доску доминошки по следующим правилам:</p><ul> <li> каждая доминошка накрывает две соседние клетки; </li><li> каждая клетка накрыта не более чем одной доминошкой; </li><li> если доминошка расположена горизонтально (она накрывает две соседние клетки в строке), обе накрытые ею клетки должны быть красными; </li><li> если доминошка расположена вертикально (она накрывает две соседние клетки в столбце), обе накрытые ею клетки должны быть синими. </li></ul><p>Пусть <span class="tex-font-style-it">ценность</span> раскраски доски — максимальное количество доминошек, которое можно расположить. Посчитайте сумму <span class="tex-font-style-it">ценностей</span> по всем $$$2^w$$$ способам раскрасить доску. Так как сумма может быть очень большой, выведите ее по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 3 \cdot 10^5$$$; $$$nm \le 3 \cdot 10^5$$$) — количество строк и столбцов, соответственно.</p><p>Затем следуют $$$n$$$ строк, в каждой из которых задана последовательность из $$$m$$$ символов. Символ под номером $$$j$$$ в $$$i$$$-й последовательности — <span class="tex-font-style-tt">*</span>, если $$$j$$$-я клетка $$$i$$$-й строки черная; иначе этот символ — <span class="tex-font-style-tt">o</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — сумму <span class="tex-font-style-it">ценностей</span> по всем $$$2^w$$$ способам раскрасить доску, взятую по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 **oo oo*o **oo </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 144 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 **oo oo** **oo </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 48 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 oo o* </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 4 oooo </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:37</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c12b68ba1490',t:'MTY5NjY2NzEzNy45NjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2100"]
1511F
1511
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>В чайнворде клетки для букв расположены в одну строку. В этой задаче мы будем рассматривать чайнворды длины $$$m$$$.</p><p>Подсказка к чайнворду — это последовательность отрезков такая, что отрезки не пересекаются между собой и покрывают все $$$m$$$ клеток. Каждый отрезок содержит описание слова в соответствующих клетках.</p><p>Особенность в том, что подсказки на самом деле две: одна последовательность находится в строке над клетками для букв, а другая — под ней. Когда эти последовательности разные, они помогают разрешить неоднозначность в ответах.</p><p>Дан словарь из $$$n$$$ слов, каждое слово состоит из строчных латинских букв. Все слова попарно различны.</p><p>Экземпляр чайнворда — это следующая тройка: </p><ul> <li> строка из $$$m$$$ строчных латинских букв; </li><li> первая подсказка: последовательность отрезков такая, что буквы, соответствующие каждому отрезку, составляют некоторое слово из словаря; </li><li> вторая подсказка: еще одна последовательность отрезков такая, что буквы, соответствующие каждому отрезку, составляют некоторое слово из словаря. </li></ul><p>Обратите внимание, что последовательности отрезков не обязаны различаться.</p><p>Два экземпляра чайнвордов считаются различными, если различаются их строки, первые подсказки <span class="tex-font-style-bf">или</span> вторые подсказки.</p><p>Посчитайте количество различных экземпляров чайнвордов. Так как их число может быть достаточно велико, выведите его остаток от деления на $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 8$$$, $$$1 \le m \le 10^9$$$) — количество слов в словаре и количество клеток с буквами.</p><p>В каждой из следующих $$$n$$$ строк записано одно слово — непустая строка из не более $$$5$$$ строчных латинских букв. Все слова попарно различные.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество различных экземпляров чайнвордов длины $$$m$$$ для данного словаря по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 ababa ab a </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 ab cd </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 100 a aa aaa aaaa aaaaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 142528942 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Здесь приведены все примеры различных чайнвордов для первого примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/734575fe874c64a4857f821627aa6847ee50e306.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Красные полоски над буквами означают отрезки первой подсказки, синие полоски под буквами означают отрезки второй подсказки.</p><p>Во втором примере возможные строки: «<span class="tex-font-style-tt">abab</span>», «<span class="tex-font-style-tt">abcd</span>», «<span class="tex-font-style-tt">cdab</span>» и «<span class="tex-font-style-tt">cdcd</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="7f05ff78a2057df9110a16236d6219b4"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7f05ff78a2057df9110a16236d6219b4'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='7f05ff78a2057df9110a16236d6219b4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='7f05ff78a2057df9110a16236d6219b4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Произведение матриц, определитель, правило Крамера, системы линейных уравнений"> матрицы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Суффиксные массивы, деревья и автоматы"> строковые суфф. структуры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='7f05ff78a2057df9110a16236d6219b4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955217"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7f05ff78a2057df9110a16236d6219b4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955217"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_24c837f07c0b94e4fbd9b0af0fcc4428c101c469"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>В чайнворде клетки для букв расположены в одну строку. В этой задаче мы будем рассматривать чайнворды длины $$$m$$$.</p><p>Подсказка к чайнворду — это последовательность отрезков такая, что отрезки не пересекаются между собой и покрывают все $$$m$$$ клеток. Каждый отрезок содержит описание слова в соответствующих клетках.</p><p>Особенность в том, что подсказки на самом деле две: одна последовательность находится в строке над клетками для букв, а другая — под ней. Когда эти последовательности разные, они помогают разрешить неоднозначность в ответах.</p><p>Дан словарь из $$$n$$$ слов, каждое слово состоит из строчных латинских букв. Все слова попарно различны.</p><p>Экземпляр чайнворда — это следующая тройка: </p><ul> <li> строка из $$$m$$$ строчных латинских букв; </li><li> первая подсказка: последовательность отрезков такая, что буквы, соответствующие каждому отрезку, составляют некоторое слово из словаря; </li><li> вторая подсказка: еще одна последовательность отрезков такая, что буквы, соответствующие каждому отрезку, составляют некоторое слово из словаря. </li></ul><p>Обратите внимание, что последовательности отрезков не обязаны различаться.</p><p>Два экземпляра чайнвордов считаются различными, если различаются их строки, первые подсказки <span class="tex-font-style-bf">или</span> вторые подсказки.</p><p>Посчитайте количество различных экземпляров чайнвордов. Так как их число может быть достаточно велико, выведите его остаток от деления на $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 8$$$, $$$1 \le m \le 10^9$$$) — количество слов в словаре и количество клеток с буквами.</p><p>В каждой из следующих $$$n$$$ строк записано одно слово — непустая строка из не более $$$5$$$ строчных латинских букв. Все слова попарно различные.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество различных экземпляров чайнвордов длины $$$m$$$ для данного словаря по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 5 ababa ab a </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 ab cd </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 100 a aa aaa aaaa aaaaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 142528942 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Здесь приведены все примеры различных чайнвордов для первого примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/734575fe874c64a4857f821627aa6847ee50e306.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Красные полоски над буквами означают отрезки первой подсказки, синие полоски под буквами означают отрезки второй подсказки.</p><p>Во втором примере возможные строки: «<span class="tex-font-style-tt">abab</span>», «<span class="tex-font-style-tt">abcd</span>», «<span class="tex-font-style-tt">cdab</span>» и «<span class="tex-font-style-tt">cdcd</span>». Все подсказки — это отрезки, которые покрывают первые две буквы и последние две буквы.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:39</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c133ea2b7b77',t:'MTY5NjY2NzEzOS4zMjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\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\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2700"]
1511G
1511
G
ru
G. Фишки на доске
<div class="problem-statement"><div class="header"><div class="title">G. Фишки на доске</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>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$$$ строк и $$$m$$$ столбцов. <span class="tex-font-style-bf">В каждой строке есть ровно одна фишка.</span></p><p>Алиса и Боб играют в следующую игру. Они выбирают два целых числа $$$l$$$ и $$$r$$$, такие, что $$$1 \le l \le r \le m$$$, и разрезают доску таким образом, что только столбцы с $$$l$$$ по $$$r$$$ (включительно) принадлежат доски. То есть все столбцы левее столбца $$$l$$$ и все столбцы правее столбца $$$r$$$ больше не являются частью доски.</p><p>После разрезания доски они начинают свою игру на оставшейся части доски (от столбца $$$l$$$ до столбца $$$r$$$). Они ходят по очереди, и первый игрок, который не может сделать ход, проигрывает. Первый ход делает Алиса, второй — Боб, третий — снова Алиса, и так далее. Во время своего хода игрок должен выбрать одну из фишек и сдвинуть ее на любое количество столбцов влево (то есть, если фишка была в столбце $$$i$$$, ее можно переместить в любой столбец $$$j &lt; i$$$, а фишки в самом левом столбце двигать нельзя). Фишки не должны покидать выбранную часть доски.</p><p>У Алисы и Боба есть $$$q$$$ пар чисел $$$L_i$$$ и $$$R_i$$$. Для каждой такой пары они хотят определить, кто выиграет, если $$$l = L_i$$$ и $$$r = R_i$$$. Обратите внимание, что эти игры рассматриваются независимо (они не влияют на положение на доске в последующих играх), и оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — количество строк и столбцов, соответственно.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le m$$$), где $$$c_i$$$ — номер столбца, в котором расположена фишка в $$$i$$$-м ряду (то есть, такое число обозначает фишку в клетке на пересечении $$$i$$$-й строки и $$$c_i$$$-го столбца).</p><p>В третьей строке задано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$).</p><p>Затем следуют $$$q$$$ строк, в $$$i$$$-й строке заданы два целых числа $$$L_i$$$ и $$$R_i$$$ ($$$1 \le L_i \le R_i \le m$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку из $$$q$$$ символов. $$$i$$$-й символ должен быть <span class="tex-font-style-tt">A</span>, если Алиса выигрывает при $$$l = L_i$$$ и $$$r = R_i$$$, или <span class="tex-font-style-tt">B</span>, если выигрывает Боб.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 10 1 3 3 7 4 2 6 9 7 2 3 1 3 1 4 1 10 5 10 8 10 9 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> BAAAAAB</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="8d8dd1459d9fde4958cab1c7d0678497"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ba11892789a53737421889bb1b086002a208952f"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='8d8dd1459d9fde4958cab1c7d0678497'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1511%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='8d8dd1459d9fde4958cab1c7d0678497'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1511">Educational Codeforces Round 107 (рейтинговый для Див. 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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='8d8dd1459d9fde4958cab1c7d0678497'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1511/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди"> игры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='8d8dd1459d9fde4958cab1c7d0678497'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="955218"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8d8dd1459d9fde4958cab1c7d0678497'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="955218"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89562" title="Educational Codeforces Round 107 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13484:13485" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89634" title="89634" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13503:13504" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1511">Задачи</a></li> <li><a href="/contest/1511/submit">Отослать</a></li> <li><a href="/contest/1511/my">Мои посылки</a></li> <li><a href="/contest/1511/status">Статус</a></li> <li><a href="/contest/1511/hacks">Взломы</a></li> <li><a href="/contest/1511/standings">Положение</a></li> <li><a href="/contest/1511/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8aa7fa4774a3da8f5fa933ebe81e1c92304e6495"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>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$$$ строк и $$$m$$$ столбцов. <span class="tex-font-style-bf">В каждой строке есть ровно одна фишка.</span></p><p>Алиса и Боб играют в следующую игру. Они выбирают два целых числа $$$l$$$ и $$$r$$$, такие, что $$$1 \le l \le r \le m$$$, и разрезают доску таким образом, что только столбцы с $$$l$$$ по $$$r$$$ (включительно) принадлежат доски. То есть все столбцы левее столбца $$$l$$$ и все столбцы правее столбца $$$r$$$ больше не являются частью доски.</p><p>После разрезания доски они начинают свою игру на оставшейся части доски (от столбца $$$l$$$ до столбца $$$r$$$). Они ходят по очереди, и первый игрок, который не может сделать ход, проигрывает. Первый ход делает Алиса, второй — Боб, третий — снова Алиса, и так далее. Во время своего хода игрок должен выбрать одну из фишек и сдвинуть ее на любое количество столбцов влево (то есть, если фишка была в столбце $$$i$$$, ее можно переместить в любой столбец $$$j &lt; i$$$, а фишки в самом левом столбце двигать нельзя). Фишки не должны покидать выбранную часть доски.</p><p>У Алисы и Боба есть $$$q$$$ пар чисел $$$L_i$$$ и $$$R_i$$$. Для каждой такой пары они хотят определить, кто выиграет, если $$$l = L_i$$$ и $$$r = R_i$$$. Обратите внимание, что эти игры рассматриваются независимо (они не влияют на положение на доске в последующих играх), и оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — количество строк и столбцов, соответственно.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le m$$$), где $$$c_i$$$ — номер столбца, в котором расположена фишка в $$$i$$$-м ряду (то есть, такое число обозначает фишку в клетке на пересечении $$$i$$$-й строки и $$$c_i$$$-го столбца).</p><p>В третьей строке задано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$).</p><p>Затем следуют $$$q$$$ строк, в $$$i$$$-й строке заданы два целых числа $$$L_i$$$ и $$$R_i$$$ ($$$1 \le L_i \le R_i \le m$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку из $$$q$$$ символов. $$$i$$$-й символ должен быть <span class="tex-font-style-tt">A</span>, если Алиса выигрывает при $$$l = L_i$$$ и $$$r = R_i$$$, или <span class="tex-font-style-tt">B</span>, если выигрывает Боб.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 10 1 3 3 7 4 2 6 9 7 2 3 1 3 1 4 1 10 5 10 8 10 9 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> BAAAAAB</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:40</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c13c895d1654',t:'MTY5NjY2NzE0MC42OTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0438\u0433\u0440\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2700"]
1512A
1512
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$$$, состоящий из $$$n$$$ ($$$n \ge 3$$$) целых положительных чисел. Известно, что в этом массиве, все числа, кроме одного, совпадают (например, в массиве $$$[4, 11, 4, 4]$$$ все числа, кроме одного, равны $$$4$$$).</p><p>Выведите номер элемента, который не совпадает с остальными. Числа в массиве пронумерованы с единицы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$3 \le n \le 100$$$) — длина массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$).</p><p>Гарантируется, что в массиве $$$a$$$ все числа, кроме одного, совпадают.</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 11 13 11 11 5 1 4 4 4 4 10 3 3 3 3 10 3 3 3 3 3 3 20 20 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 5 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="7bb021f5723c9434b0992e40b5e37202"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='7bb021f5723c9434b0992e40b5e37202'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='7bb021f5723c9434b0992e40b5e37202'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='7bb021f5723c9434b0992e40b5e37202'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='7bb021f5723c9434b0992e40b5e37202'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953474"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7bb021f5723c9434b0992e40b5e37202'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953474"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e7f7aca5fc7fc20a61ea01cdbe6bab1ed800df1b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$, состоящий из $$$n$$$ ($$$n \ge 3$$$) целых положительных чисел. Известно, что в этом массиве, все числа, кроме одного, совпадают (например, в массиве $$$[4, 11, 4, 4]$$$ все числа, кроме одного, равны $$$4$$$).</p><p>Выведите номер элемента, который не совпадает с остальными. Числа в массиве пронумерованы с единицы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$3 \le n \le 100$$$) — длина массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$).</p><p>Гарантируется, что в массиве $$$a$$$ все числа, кроме одного, совпадают.</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 11 13 11 11 5 1 4 4 4 4 10 3 3 3 3 10 3 3 3 3 3 3 20 20 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 5 3 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:42</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1451864164e',t:'MTY5NjY2NzE0Mi4xMTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\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"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1512B
1512
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 \times n$$$ отмечены две клетки. Они могут находиться в одной строке или столбце.</p><p>Необходимо отметить еще две клетки так, чтобы они являлись углами какого-либо прямоугольника со сторонами, параллельными осям координат.</p><p>Например, если $$$n=4$$$ и прямоугольное поле выглядит следующим образом (в отмеченных клетках находятся звездочки):</p><p>$$$$$$ \begin{matrix} . &amp; . &amp; * &amp; . \\ . &amp; . &amp; . &amp; . \\ * &amp; . &amp; . &amp; . \\ . &amp; . &amp; . &amp; . \\ \end{matrix} $$$$$$</p><p>То можно отметить еще две клетки следующим образом:</p><p>$$$$$$ \begin{matrix} * &amp; . &amp; * &amp; . \\ . &amp; . &amp; . &amp; . \\ * &amp; . &amp; * &amp; . \\ . &amp; . &amp; . &amp; . \\ \end{matrix} $$$$$$</p><p>Если существует несколько возможных решений, то выведите любое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 400$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится целое число $$$n$$$ ($$$2 \le n \le 400$$$) — количество строк и столбцов в таблице.</p><p>В следующих $$$n$$$ строках находится по $$$n$$$ символов '<span class="tex-font-style-tt">.</span>' или '<span class="tex-font-style-tt">*</span>' обозначающих пустые и отмеченные клетки, соответственно.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$400$$$.</p><p>Гарантируется, что на поле есть ровно две звездочки. Они могут находиться в одной строке или столбце.</p><p>Гарантируется, что решение существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ строк по $$$n$$$ символов — поле с четырьмя отмеченными звездочками, соответствующее условию. Если ответов несколько, то выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 ..*. .... *... .... 2 *. .* 2 .* .* 3 *.* ... ... 5 ..... ..*.. ..... .*... ..... 4 .... .... *... *... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> *.*. .... *.*. .... ** ** ** ** *.* *.* ... ..... .**.. ..... .**.. ..... .... .... **.. **.. </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="261944334ff48d1b03760b82f05a9896"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='261944334ff48d1b03760b82f05a9896'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='261944334ff48d1b03760b82f05a9896'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='261944334ff48d1b03760b82f05a9896'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='261944334ff48d1b03760b82f05a9896'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953475"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='261944334ff48d1b03760b82f05a9896'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953475"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d134ae622e7dfcce5e96a0d188ab4abfe3df7493"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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 \times n$$$ отмечены две клетки. Они могут находиться в одной строке или столбце.</p><p>Необходимо отметить еще две клетки так, чтобы они являлись углами какого-либо прямоугольника со сторонами, параллельными осям координат.</p><p>Например, если $$$n=4$$$ и прямоугольное поле выглядит следующим образом (в отмеченных клетках находятся звездочки):</p><p>$$$$$$ \begin{matrix} . &amp; . &amp; * &amp; . \\ . &amp; . &amp; . &amp; . \\ * &amp; . &amp; . &amp; . \\ . &amp; . &amp; . &amp; . \\ \end{matrix} $$$$$$</p><p>То можно отметить еще две клетки следующим образом:</p><p>$$$$$$ \begin{matrix} * &amp; . &amp; * &amp; . \\ . &amp; . &amp; . &amp; . \\ * &amp; . &amp; * &amp; . \\ . &amp; . &amp; . &amp; . \\ \end{matrix} $$$$$$</p><p>Если существует несколько возможных решений, то выведите любое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 400$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится целое число $$$n$$$ ($$$2 \le n \le 400$$$) — количество строк и столбцов в таблице.</p><p>В следующих $$$n$$$ строках находится по $$$n$$$ символов '<span class="tex-font-style-tt">.</span>' или '<span class="tex-font-style-tt">*</span>' обозначающих пустые и отмеченные клетки, соответственно.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$400$$$.</p><p>Гарантируется, что на поле есть ровно две звездочки. Они могут находиться в одной строке или столбце.</p><p>Гарантируется, что решение существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ строк по $$$n$$$ символов — поле с четырьмя отмеченными звездочками, соответствующее условию. Если ответов несколько, то выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 ..*. .... *... .... 2 *. .* 2 .* .* 3 *.* ... ... 5 ..... ..*.. ..... .*... ..... 4 .... .... *... *... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> *.*. .... *.*. .... ** ** ** ** *.* *.* ... ..... .**.. ..... .**.. ..... .... .... **.. **.. </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:43</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c14dda940004',t:'MTY5NjY2NzE0My41NzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1512C
1512
C
ru
C. A-B палиндром
<div class="problem-statement"><div class="header"><div class="title">C. 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>Вам дана строка $$$s$$$, состоящая из символов '<span class="tex-font-style-tt">0</span>', '<span class="tex-font-style-tt">1</span>' и '<span class="tex-font-style-tt">?</span>'. Вам необходимо заменить все символы '<span class="tex-font-style-tt">?</span>' в строке $$$s$$$ на '<span class="tex-font-style-tt">0</span>' или '<span class="tex-font-style-tt">1</span>' так, чтобы строка стала палиндромом и чтобы в ней было <span class="tex-font-style-bf">ровно</span> $$$a$$$ символов '<span class="tex-font-style-tt">0</span>' и <span class="tex-font-style-bf">ровно</span> $$$b$$$ символов '<span class="tex-font-style-tt">1</span>'. Обратите внимание, что каждый из символов '<span class="tex-font-style-tt">?</span>' вы заменяете <span class="tex-font-style-bf">независимо</span> от других.</p><p>Строка $$$t$$$ длины $$$n$$$ называется палиндромом, если для всех $$$i$$$ ($$$1 \le i \le n$$$) верно равенство $$$t[i] = t[n-i+1]$$$.</p><p>Например, если $$$s=$$$«<span class="tex-font-style-tt">01?????0</span>», $$$a=4$$$ и $$$b=4$$$, то можно заменить символы '<span class="tex-font-style-tt">?</span>' следующими способами: </p><ul> <li> «<span class="tex-font-style-tt">01011010</span>»; </li><li> «<span class="tex-font-style-tt">01100110</span>». </li></ul><p>Для заданной строки $$$s$$$ и чисел $$$a$$$ и $$$b$$$ замените все символы '<span class="tex-font-style-tt">?</span>' в строке $$$s$$$ на '<span class="tex-font-style-tt">0</span>' или '<span class="tex-font-style-tt">1</span>' так, чтобы строка стала палиндромом и чтобы в ней было <span class="tex-font-style-bf">ровно</span> $$$a$$$ символов '<span class="tex-font-style-tt">0</span>' и <span class="tex-font-style-bf">ровно</span> $$$b$$$ символов '<span class="tex-font-style-tt">1</span>'.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$a$$$ и $$$b$$$ ($$$0 \le a, b \le 2 \cdot 10^5$$$, $$$a + b \ge 1$$$).</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длины $$$a+b$$$, состоящую из символов '<span class="tex-font-style-tt">0</span>', '<span class="tex-font-style-tt">1</span>' и '<span class="tex-font-style-tt">?</span>'.</p><p>Гарантируется, что сумма длин строк $$$s$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">-1</span>», если нельзя заменить все символы '<span class="tex-font-style-tt">?</span>' в строке $$$s$$$ на '<span class="tex-font-style-tt">0</span>' или '<span class="tex-font-style-tt">1</span>' так, чтобы строка стала палиндромом и чтобы в ней было <span class="tex-font-style-bf">ровно</span> $$$a$$$ символов '<span class="tex-font-style-tt">0</span>' и <span class="tex-font-style-bf">ровно</span> $$$b$$$ символов '<span class="tex-font-style-tt">1</span>'; </li><li> строку, которая получается в результате замены, в противном случае. </li></ul><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 4 4 01?????0 3 3 ?????? 1 0 ? 2 2 0101 2 2 01?0 0 1 0 0 3 1?1 2 2 ?00? 4 3 ??010?0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 01011010 -1 0 -1 0110 -1 111 1001 0101010 </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="2bbf64ca5c05b8340e5d0091a7f5a618"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2bbf64ca5c05b8340e5d0091a7f5a618'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='2bbf64ca5c05b8340e5d0091a7f5a618'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2bbf64ca5c05b8340e5d0091a7f5a618'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='2bbf64ca5c05b8340e5d0091a7f5a618'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953476"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2bbf64ca5c05b8340e5d0091a7f5a618'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953476"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_439ea9fd35d28f6d377aa1e968496812fb057b6b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. 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>Вам дана строка $$$s$$$, состоящая из символов '<span class="tex-font-style-tt">0</span>', '<span class="tex-font-style-tt">1</span>' и '<span class="tex-font-style-tt">?</span>'. Вам необходимо заменить все символы '<span class="tex-font-style-tt">?</span>' в строке $$$s$$$ на '<span class="tex-font-style-tt">0</span>' или '<span class="tex-font-style-tt">1</span>' так, чтобы строка стала палиндромом и чтобы в ней было <span class="tex-font-style-bf">ровно</span> $$$a$$$ символов '<span class="tex-font-style-tt">0</span>' и <span class="tex-font-style-bf">ровно</span> $$$b$$$ символов '<span class="tex-font-style-tt">1</span>'. Обратите внимание, что каждый из символов '<span class="tex-font-style-tt">?</span>' вы заменяете <span class="tex-font-style-bf">независимо</span> от других.</p><p>Строка $$$t$$$ длины $$$n$$$ называется палиндромом, если для всех $$$i$$$ ($$$1 \le i \le n$$$) верно равенство $$$t[i] = t[n-i+1]$$$.</p><p>Например, если $$$s=$$$«<span class="tex-font-style-tt">01?????0</span>», $$$a=4$$$ и $$$b=4$$$, то можно заменить символы '<span class="tex-font-style-tt">?</span>' следующими способами: </p><ul> <li> «<span class="tex-font-style-tt">01011010</span>»; </li><li> «<span class="tex-font-style-tt">01100110</span>». </li></ul><p>Для заданной строки $$$s$$$ и чисел $$$a$$$ и $$$b$$$ замените все символы '<span class="tex-font-style-tt">?</span>' в строке $$$s$$$ на '<span class="tex-font-style-tt">0</span>' или '<span class="tex-font-style-tt">1</span>' так, чтобы строка стала палиндромом и чтобы в ней было <span class="tex-font-style-bf">ровно</span> $$$a$$$ символов '<span class="tex-font-style-tt">0</span>' и <span class="tex-font-style-bf">ровно</span> $$$b$$$ символов '<span class="tex-font-style-tt">1</span>'.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$a$$$ и $$$b$$$ ($$$0 \le a, b \le 2 \cdot 10^5$$$, $$$a + b \ge 1$$$).</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длины $$$a+b$$$, состоящую из символов '<span class="tex-font-style-tt">0</span>', '<span class="tex-font-style-tt">1</span>' и '<span class="tex-font-style-tt">?</span>'.</p><p>Гарантируется, что сумма длин строк $$$s$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">-1</span>», если нельзя заменить все символы '<span class="tex-font-style-tt">?</span>' в строке $$$s$$$ на '<span class="tex-font-style-tt">0</span>' или '<span class="tex-font-style-tt">1</span>' так, чтобы строка стала палиндромом и чтобы в ней было <span class="tex-font-style-bf">ровно</span> $$$a$$$ символов '<span class="tex-font-style-tt">0</span>' и <span class="tex-font-style-bf">ровно</span> $$$b$$$ символов '<span class="tex-font-style-tt">1</span>'; </li><li> строку, которая получается в результате замены, в противном случае. </li></ul><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 4 4 01?????0 3 3 ?????? 1 0 ? 2 2 0101 2 2 01?0 0 1 0 0 3 1?1 2 2 ?00? 4 3 ??010?0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 01011010 -1 0 -1 0110 -1 111 1001 0101010 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:44</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c156ed0e9d93',t:'MTY5NjY2NzE0NC44OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1200"]
1512D
1512
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$$$ и массив $$$b_1, b_2, \ldots, b_{n+2}$$$, полученный согласно следующему алгоритму: </p><ul> <li> был загадан некоторый массив $$$a_1, a_2, \ldots, a_n$$$; </li><li> массив $$$a$$$ записали в массив $$$b$$$, т.е. $$$b_i = a_i$$$ ($$$1 \le i \le n$$$); </li><li> $$$(n+1)$$$-м элементом массива $$$b$$$ записали сумму чисел в массиве $$$a$$$, т.е. $$$b_{n+1} = a_1+a_2+\ldots+a_n$$$; </li><li> $$$(n+2)$$$-м элементом массива $$$b$$$ записали некоторое число $$$x$$$ ($$$1 \le x \le 10^9$$$), т.е. $$$b_{n+2} = x$$$; </li><li> массив $$$b$$$ был перемешан. </li></ul> <p>Например, массив $$$b=[2, 3, 7, 12 ,2]$$$ мог быть получен следующими способами: </p><ul> <li> $$$a=[2, 2, 3]$$$ и $$$x=12$$$; </li><li> $$$a=[3, 2, 7]$$$ и $$$x=2$$$. </li></ul><p>Для заданного массива $$$b$$$ найдите любой массив $$$a$$$, который мог быть загадан изначально.</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$$$).</p><p>Вторая строка каждого набора содержит $$$n+2$$$ целых числа $$$b_1, b_2, \ldots, b_{n+2}$$$ ($$$1 \le b_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">-1</span>», если массив $$$b$$$ не мог быть получен ни по какому массиву $$$a$$$; </li><li> $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$, иначе. </li></ul><p>Если существует несколько массивов $$$a$$$, то можете выводить любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 7 12 2 4 9 1 7 1 6 5 5 18 2 2 3 2 9 2 3 2 6 9 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 7 -1 2 2 2 3 9 1 2 6 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a19a61767afb961bbc1cd0508f8a783c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a19a61767afb961bbc1cd0508f8a783c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='a19a61767afb961bbc1cd0508f8a783c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a19a61767afb961bbc1cd0508f8a783c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='a19a61767afb961bbc1cd0508f8a783c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953478"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a19a61767afb961bbc1cd0508f8a783c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953478"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_db6fdfc75766fcf0e1e0aee95ebcc7f209ff823f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$ и массив $$$b_1, b_2, \ldots, b_{n+2}$$$, полученный согласно следующему алгоритму: </p><ul> <li> был загадан некоторый массив $$$a_1, a_2, \ldots, a_n$$$; </li><li> массив $$$a$$$ записали в массив $$$b$$$, т.е. $$$b_i = a_i$$$ ($$$1 \le i \le n$$$); </li><li> $$$(n+1)$$$-м элементом массива $$$b$$$ записали сумму чисел в массиве $$$a$$$, т.е. $$$b_{n+1} = a_1+a_2+\ldots+a_n$$$; </li><li> $$$(n+2)$$$-м элементом массива $$$b$$$ записали некоторое число $$$x$$$ ($$$1 \le x \le 10^9$$$), т.е. $$$b_{n+2} = x$$$; </li><li> массив $$$b$$$ был перемешан. </li></ul> <p>Например, массив $$$b=[2, 3, 7, 12 ,2]$$$ мог быть получен следующими способами: </p><ul> <li> $$$a=[2, 2, 3]$$$ и $$$x=12$$$; </li><li> $$$a=[3, 2, 7]$$$ и $$$x=2$$$. </li></ul><p>Для заданного массива $$$b$$$ найдите любой массив $$$a$$$, который мог быть загадан изначально.</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$$$).</p><p>Вторая строка каждого набора содержит $$$n+2$$$ целых числа $$$b_1, b_2, \ldots, b_{n+2}$$$ ($$$1 \le b_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">-1</span>», если массив $$$b$$$ не мог быть получен ни по какому массиву $$$a$$$; </li><li> $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$, иначе. </li></ul><p>Если существует несколько массивов $$$a$$$, то можете выводить любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 7 12 2 4 9 1 7 1 6 5 5 18 2 2 3 2 9 2 3 2 6 9 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 7 -1 2 2 2 3 9 1 2 6 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:46</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c15f4e1875ab',t:'MTY5NjY2NzE0Ni4yNjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1200"]
1512E
1512
E
ru
E. Перестановка по сумме
<div class="problem-statement"><div class="header"><div class="title">E. Перестановка по сумме</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановка — это последовательность длины $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$, в которой все числа встречаются ровно по одному разу. Например, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — перестановки, а $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — нет. </p><p>Поликарпу дали четыре целых числа $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n)$$$ и $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$) и попросили найти перестановку $$$p$$$ чисел от $$$1$$$ до $$$n$$$, обладающую следующим свойством: </p><ul> <li> $$$s = p_l + p_{l+1} + \ldots + p_r$$$. </li></ul><p>Например, для $$$n=5$$$, $$$l=3$$$, $$$r=5$$$ и $$$s=8$$$ подходят следующие перестановки (перечислены не все варианты): </p><ul> <li> $$$p = [3, 4, 5, 2, 1]$$$; </li><li> $$$p = [5, 2, 4, 3, 1]$$$; </li><li> $$$p = [5, 2, 1, 3, 4]$$$. </li></ul> Но, например, не существует ни одной перестановки, подходящей под условие выше для $$$n=4$$$, $$$l=1$$$, $$$r=1$$$ и $$$s=5$$$.<p>Помогите Поликарпу для заданных $$$n$$$, $$$l$$$, $$$r$$$ и $$$s$$$ найти перестановку чисел от $$$1$$$ до $$$n$$$, подходящую под условие выше. Если существует несколько подходящих перестановок, выведите любую из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных характеризуется четырьмя целыми числами $$$n$$$ ($$$1 \le n \le 500$$$), $$$l$$$ ($$$1 \le l \le n$$$), $$$r$$$ ($$$l \le r \le n$$$), $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных в отдельной строке выведите: </p><ul> <li> $$$n$$$ целых чисел — перестановку длины $$$n$$$, обладающую свойством из условия, если такая перестановка существует; </li><li> <span class="tex-font-style-tt">-1</span>, иначе. </li></ul><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 3 5 5 3 4 1 3 1 2 4 2 2 2 2 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 4 5 -1 1 3 2 1 2 -1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9b355ebe342ac89e7d658769216d8046"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='9b355ebe342ac89e7d658769216d8046'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='9b355ebe342ac89e7d658769216d8046'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='9b355ebe342ac89e7d658769216d8046'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='9b355ebe342ac89e7d658769216d8046'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953477"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9b355ebe342ac89e7d658769216d8046'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953477"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d81a5bb818b8fad67720de7dd13fef4e7b424270"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Перестановка по сумме</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановка — это последовательность длины $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$, в которой все числа встречаются ровно по одному разу. Например, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — перестановки, а $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — нет. </p><p>Поликарпу дали четыре целых числа $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n)$$$ и $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$) и попросили найти перестановку $$$p$$$ чисел от $$$1$$$ до $$$n$$$, обладающую следующим свойством: </p><ul> <li> $$$s = p_l + p_{l+1} + \ldots + p_r$$$. </li></ul><p>Например, для $$$n=5$$$, $$$l=3$$$, $$$r=5$$$ и $$$s=8$$$ подходят следующие перестановки (перечислены не все варианты): </p><ul> <li> $$$p = [3, 4, 5, 2, 1]$$$; </li><li> $$$p = [5, 2, 4, 3, 1]$$$; </li><li> $$$p = [5, 2, 1, 3, 4]$$$. </li></ul> Но, например, не существует ни одной перестановки, подходящей под условие выше для $$$n=4$$$, $$$l=1$$$, $$$r=1$$$ и $$$s=5$$$.<p>Помогите Поликарпу для заданных $$$n$$$, $$$l$$$, $$$r$$$ и $$$s$$$ найти перестановку чисел от $$$1$$$ до $$$n$$$, подходящую под условие выше. Если существует несколько подходящих перестановок, выведите любую из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных характеризуется четырьмя целыми числами $$$n$$$ ($$$1 \le n \le 500$$$), $$$l$$$ ($$$1 \le l \le n$$$), $$$r$$$ ($$$l \le r \le n$$$), $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных в отдельной строке выведите: </p><ul> <li> $$$n$$$ целых чисел — перестановку длины $$$n$$$, обладающую свойством из условия, если такая перестановка существует; </li><li> <span class="tex-font-style-tt">-1</span>, иначе. </li></ul><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 3 5 5 3 4 1 3 1 2 4 2 2 2 2 2 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 4 5 -1 1 3 2 1 2 -1 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:47</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c167cb0a16db',t:'MTY5NjY2NzE0Ny42MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1600"]
1512F
1512
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>Поликарп мечтает о покупке нового компьютера, который стоит $$$c$$$ тугриков. Для этого он хочет устроиться программистом в большую компанию.</p><p>В компании Поликарпа есть $$$n$$$ должностей, пронумерованных начиная с единицы. Сотрудник на должности $$$i$$$ каждый день зарабатывает $$$a[i]$$$ тугриков. Чем выше номер должности, тем больше тугриков получает сотрудник. Изначально Поликарп устраивается на должность с номером $$$1$$$ и имеет $$$0$$$ тугриков.</p><p>Каждый день Поликарп может сделать одно из двух действий: </p><ul> <li> Если Поликарп находится на должности $$$x$$$, то он может заработать $$$a[x]$$$ тугриков; </li><li> Если Поликарп находится на должности $$$x$$$ ($$$x &lt; n$$$) и имеет хотя бы $$$b[x]$$$ тугриков, то он может потратить $$$b[x]$$$ тугриков на онлайн-курс и перейти на должность $$$x+1$$$. </li></ul><p>Например, если $$$n=4$$$, $$$c=15$$$, $$$a=[1, 3, 10, 11]$$$, $$$b=[1, 2, 7]$$$, то Поликарп может действовать так: </p><ul> <li> В первый день Поликарп находится на должности $$$1$$$ и зарабатывает $$$1$$$ тугрик. Теперь у него есть $$$1$$$ тугрик; </li><li> Во второй день Поликарп находится на должности $$$1$$$ и переходит на должность $$$2$$$. Теперь у него есть $$$0$$$ тугриков; </li><li> В третий день Поликарп находится на должности $$$2$$$ и зарабатывает $$$3$$$ тугрика. Теперь у него есть $$$3$$$ тугрика; </li><li> В четвертый день Поликарп находится на должности $$$2$$$ и переходит на должность $$$3$$$. Теперь у него есть $$$1$$$ тугрик; </li><li> В пятый день Поликарп находится на должности $$$3$$$ и зарабатывает $$$10$$$ тугриков. Теперь у него есть $$$11$$$ тугриков; </li><li> В шестой день Поликарп находится на должности $$$3$$$ и зарабатывает $$$10$$$ тугриков. Теперь у него есть $$$21$$$ тугриков; </li><li> Спустя шесть дней, Поликарп может купить себе новый компьютер. </li></ul><p>Найдите минимальное количество дней, через которое Поликарп сможет купить себе новый компьютер.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le c \le 10^9$$$) — количество должностей в компании и стоимость нового компьютера.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1 \le a_2 \le \ldots \le a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Третья строка каждого набора входных данных содержит $$$n - 1$$$ целое число $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$1 \le b_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышаем $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество дней, через которое Поликарп сможет купить себе новый компьютер.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 15 1 3 10 11 1 2 7 4 100 1 5 10 50 3 14 12 2 1000000000 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 13 1000000000 </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="898b2d4e7804d5f28b68f5af1843198c"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='898b2d4e7804d5f28b68f5af1843198c'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='898b2d4e7804d5f28b68f5af1843198c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='898b2d4e7804d5f28b68f5af1843198c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='898b2d4e7804d5f28b68f5af1843198c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953479"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='898b2d4e7804d5f28b68f5af1843198c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953479"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0c117ae035932e836af623517374a0960a39438b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Поликарп мечтает о покупке нового компьютера, который стоит $$$c$$$ тугриков. Для этого он хочет устроиться программистом в большую компанию.</p><p>В компании Поликарпа есть $$$n$$$ должностей, пронумерованных начиная с единицы. Сотрудник на должности $$$i$$$ каждый день зарабатывает $$$a[i]$$$ тугриков. Чем выше номер должности, тем больше тугриков получает сотрудник. Изначально Поликарп устраивается на должность с номером $$$1$$$ и имеет $$$0$$$ тугриков.</p><p>Каждый день Поликарп может сделать одно из двух действий: </p><ul> <li> Если Поликарп находится на должности $$$x$$$, то он может заработать $$$a[x]$$$ тугриков; </li><li> Если Поликарп находится на должности $$$x$$$ ($$$x &lt; n$$$) и имеет хотя бы $$$b[x]$$$ тугриков, то он может потратить $$$b[x]$$$ тугриков на онлайн-курс и перейти на должность $$$x+1$$$. </li></ul><p>Например, если $$$n=4$$$, $$$c=15$$$, $$$a=[1, 3, 10, 11]$$$, $$$b=[1, 2, 7]$$$, то Поликарп может действовать так: </p><ul> <li> В первый день Поликарп находится на должности $$$1$$$ и зарабатывает $$$1$$$ тугрик. Теперь у него есть $$$1$$$ тугрик; </li><li> Во второй день Поликарп находится на должности $$$1$$$ и переходит на должность $$$2$$$. Теперь у него есть $$$0$$$ тугриков; </li><li> В третий день Поликарп находится на должности $$$2$$$ и зарабатывает $$$3$$$ тугрика. Теперь у него есть $$$3$$$ тугрика; </li><li> В четвертый день Поликарп находится на должности $$$2$$$ и переходит на должность $$$3$$$. Теперь у него есть $$$1$$$ тугрик; </li><li> В пятый день Поликарп находится на должности $$$3$$$ и зарабатывает $$$10$$$ тугриков. Теперь у него есть $$$11$$$ тугриков; </li><li> В шестой день Поликарп находится на должности $$$3$$$ и зарабатывает $$$10$$$ тугриков. Теперь у него есть $$$21$$$ тугриков; </li><li> Спустя шесть дней, Поликарп может купить себе новый компьютер. </li></ul><p>Найдите минимальное количество дней, через которое Поликарп сможет купить себе новый компьютер.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le c \le 10^9$$$) — количество должностей в компании и стоимость нового компьютера.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1 \le a_2 \le \ldots \le a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p><p>Третья строка каждого набора входных данных содержит $$$n - 1$$$ целое число $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$1 \le b_i \le 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышаем $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество дней, через которое Поликарп сможет купить себе новый компьютер.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 15 1 3 10 11 1 2 7 4 100 1 5 10 50 3 14 12 2 1000000000 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 13 1000000000 </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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:48</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1704da77b7b',t:'MTY5NjY2NzE0OC45ODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1900"]
1512G
1512
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>Обозначим за $$$d(n)$$$ сумму всех делителей числа $$$n$$$, т.е. $$$d(n) = \sum\limits_{k | n} k$$$.</p><p>Например, $$$d(1) = 1$$$, $$$d(4) = 1+2+4=7$$$, $$$d(6) = 1+2+3+6=12$$$.</p><p>Для заданного числа $$$c$$$, найдите минимальное $$$n$$$ такое, что $$$d(n) = c$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных характеризуется одним целым числом $$$c$$$ ($$$1 \le c \le 10^7$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">-1</span>», если не существует $$$n$$$, такого что $$$d(n) = c$$$; </li><li> $$$n$$$, иначе. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 12 1 2 3 4 5 6 7 8 9 10 39 691 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 2 3 -1 5 4 7 -1 -1 18 -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="a705b35145643eff99a88c33c61d6c7a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="ae1a907ad3c87d646db64aa19f7e3420b49e7585"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a705b35145643eff99a88c33c61d6c7a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1512%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='a705b35145643eff99a88c33c61d6c7a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1512">Codeforces Round 713 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a705b35145643eff99a88c33c61d6c7a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1512/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='a705b35145643eff99a88c33c61d6c7a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="953480"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a705b35145643eff99a88c33c61d6c7a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="953480"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89476" title="Codeforces Round #713 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13471:13472" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89535" title="Codeforces Round #713 (Div. 3) Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13480:13481" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1512">Задачи</a></li> <li><a href="/contest/1512/submit">Отослать</a></li> <li><a href="/contest/1512/my">Мои посылки</a></li> <li><a href="/contest/1512/status">Статус</a></li> <li><a href="/contest/1512/hacks">Взломы</a></li> <li><a href="/contest/1512/standings">Положение</a></li> <li><a href="/contest/1512/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_053d71d755b4de6d42c9d4aa93ef7737e4e67b02"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Обозначим за $$$d(n)$$$ сумму всех делителей числа $$$n$$$, т.е. $$$d(n) = \sum\limits_{k | n} k$$$.</p><p>Например, $$$d(1) = 1$$$, $$$d(4) = 1+2+4=7$$$, $$$d(6) = 1+2+3+6=12$$$.</p><p>Для заданного числа $$$c$$$, найдите минимальное $$$n$$$ такое, что $$$d(n) = c$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных характеризуется одним целым числом $$$c$$$ ($$$1 \le c \le 10^7$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">-1</span>», если не существует $$$n$$$, такого что $$$d(n) = c$$$; </li><li> $$$n$$$, иначе. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 12 1 2 3 4 5 6 7 8 9 10 39 691 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 -1 2 3 -1 5 4 7 -1 -1 18 -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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:50</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c178dce77b43',t:'MTY5NjY2NzE1MC4zNTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1700"]
1513A
1513
A
ru
A. Массив и пики
<div class="problem-statement"><div class="header"><div class="title">A. Массив и пики</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Последовательность $$$n$$$ целых чисел называется перестановкой, если она содержит все целые числа от $$$1$$$ до $$$n$$$ по одному разу.</p><p>Вам даны два целых числа $$$n$$$ и $$$k$$$. Постройте перестановку $$$a$$$ чисел от $$$1$$$ до $$$n$$$, в которой <span class="tex-font-style-bf">ровно</span> $$$k$$$ пиков. Индекс $$$i$$$ массива $$$a$$$ размера $$$n$$$ называется пиком, если $$$1 &lt; i &lt; n$$$, $$$a_i \gt a_{i-1}$$$ и $$$a_i \gt a_{i+1}$$$. Если такой перестановки не существует, выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>Далее следуют $$$t$$$ строк, каждая из которых содержит два целых числа $$$n$$$ ($$$1 \leq n \leq 100$$$) и $$$k$$$ ($$$0 \leq k \leq n$$$) — требуемую длину массива и необходимое число пиков.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Для каждого набора входных данных, если необходимой перестановки не существует, выведите $$$-1$$$. В противном случае выведите строку, содержащую $$$n$$$ целых чисел, образующих перестановку целых чисел $$$1$$$ до $$$n$$$, содержащую ровно $$$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> 5 1 0 5 2 6 6 2 1 6 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 4 1 5 3 -1 -1 1 3 6 5 4 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных ответом является, например, $$$a = [2,4,1,5,3]$$$. Здесь индексы $$$i=2$$$ и $$$i=4$$$ являются пиками. Это так, потому что $$$(a_{2} \gt a_{1} $$$, $$$a_{2} \gt a_{3})$$$, а также $$$(a_{4} \gt a_{3}$$$, $$$a_{4} \gt a_{5})$$$. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="56eb83edfb023c24d9b286c99860c61f"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cd03549350a7c14847d214f045ac3a7848c939ec"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='56eb83edfb023c24d9b286c99860c61f'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1513%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='56eb83edfb023c24d9b286c99860c61f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1513">Divide by Zero 2021 and Codeforces Round 714 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='56eb83edfb023c24d9b286c99860c61f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1513/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound 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='56eb83edfb023c24d9b286c99860c61f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="954478"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='56eb83edfb023c24d9b286c99860c61f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="954478"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89520" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13479" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89550" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13488" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1513">Задачи</a></li> <li><a href="/contest/1513/submit">Отослать</a></li> <li><a href="/contest/1513/my">Мои посылки</a></li> <li><a href="/contest/1513/status">Статус</a></li> <li><a href="/contest/1513/hacks">Взломы</a></li> <li><a href="/contest/1513/room/1">Комната</a></li> <li><a href="/contest/1513/standings">Положение</a></li> <li><a href="/contest/1513/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2656609ea28c884a774c3ee5b235de0c1da593c6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Массив и пики</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Последовательность $$$n$$$ целых чисел называется перестановкой, если она содержит все целые числа от $$$1$$$ до $$$n$$$ по одному разу.</p><p>Вам даны два целых числа $$$n$$$ и $$$k$$$. Постройте перестановку $$$a$$$ чисел от $$$1$$$ до $$$n$$$, в которой <span class="tex-font-style-bf">ровно</span> $$$k$$$ пиков. Индекс $$$i$$$ массива $$$a$$$ размера $$$n$$$ называется пиком, если $$$1 &lt; i &lt; n$$$, $$$a_i \gt a_{i-1}$$$ и $$$a_i \gt a_{i+1}$$$. Если такой перестановки не существует, выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>Далее следуют $$$t$$$ строк, каждая из которых содержит два целых числа $$$n$$$ ($$$1 \leq n \leq 100$$$) и $$$k$$$ ($$$0 \leq k \leq n$$$) — требуемую длину массива и необходимое число пиков.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Для каждого набора входных данных, если необходимой перестановки не существует, выведите $$$-1$$$. В противном случае выведите строку, содержащую $$$n$$$ целых чисел, образующих перестановку целых чисел $$$1$$$ до $$$n$$$, содержащую ровно $$$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> 5 1 0 5 2 6 6 2 1 6 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 4 1 5 3 -1 -1 1 3 6 5 4 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных ответом является, например, $$$a = [2,4,1,5,3]$$$. Здесь индексы $$$i=2$$$ и $$$i=4$$$ являются пиками. Это так, потому что $$$(a_{2} \gt a_{1} $$$, $$$a_{2} \gt a_{3})$$$, а также $$$(a_{4} \gt a_{3}$$$, $$$a_{4} \gt a_{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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:51</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1817a6b00b4',t:'MTY5NjY2NzE1MS43ODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*800"]
1513B
1513
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$$$ ($$$n \ge 2$$$) неотрицательных целых чисел $$$a_1, a_2, \dots, a_n$$$ называется хорошей, если для всех $$$i$$$ от $$$1$$$ до $$$n-1$$$ выполняется следующее условие: $$$$$$a_1 \: \&amp; \: a_2 \: \&amp; \: \dots \: \&amp; \: a_i = a_{i+1} \: \&amp; \: a_{i+2} \: \&amp; \: \dots \: \&amp; \: a_n,$$$$$$ где $$$\&amp;$$$ обозначает операцию <a href="https://bit.ly/2LBLVWv">побитового И</a>.</p><p>Вам дан массив $$$a$$$ размера $$$n$$$ ($$$n \geq 2$$$). Найдите количество перестановок $$$p$$$ чисел от $$$1$$$ до $$$n$$$, для которых последовательность $$$a_{p_1}$$$, $$$a_{p_2}$$$, ... ,$$$a_{p_n}$$$ является хорошей. Так как это число может быть большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — размер массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, где $$$i$$$-я строка содержит количество хороших перестановок в $$$i$$$-м наборе входных данных по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 1 1 5 1 2 3 4 5 5 0 2 0 3 0 4 1 3 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 0 36 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных все числа равны, поэтому все перестановки являются хорошими. Всего есть $$$6$$$ перестановок чисел от $$$1$$$ до $$$3$$$: $$$[1,2,3]$$$, $$$[1,3,2]$$$, $$$[2,1,3]$$$, $$$[2,3,1]$$$, $$$[3,1,2]$$$, $$$[3,2,1]$$$.</p><p>Во втором наборе входных данных можно показать, что хороших перестановок нет.</p><p>В третьем наборе входных данных существуют $$$36$$$ хороших перестановок. Например, перестановка $$$[1,5,4,2,3]$$$ дает последовательность $$$s=[0,0,3,2,0]$$$. Она хорошая, так как </p><ul> <li> $$$ s_1 = s_2 \: \&amp; \: s_3 \: \&amp; \: s_4 \: \&amp; \: s_5 = 0$$$, </li><li> $$$ s_1 \: \&amp; \: s_2 = s_3 \: \&amp; \: s_4 \: \&amp; \: s_5 = 0$$$, </li><li> $$$ s_1 \: \&amp; \: s_2 \: \&amp; \: s_3 = s_4 \: \&amp; \: s_5 = 0$$$, </li><li> $$$ s_1 \: \&amp; \: s_2 \: \&amp; \: s_3 \: \&amp; \: s_4 = s_5 = 0$$$. </li></ul><p> </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a4f45d9d81d63dd83484edf0569ac5cc"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cd03549350a7c14847d214f045ac3a7848c939ec"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a4f45d9d81d63dd83484edf0569ac5cc'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1513%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='a4f45d9d81d63dd83484edf0569ac5cc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1513">Divide by Zero 2021 and Codeforces Round 714 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a4f45d9d81d63dd83484edf0569ac5cc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1513/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='a4f45d9d81d63dd83484edf0569ac5cc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="954479"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a4f45d9d81d63dd83484edf0569ac5cc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="954479"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89520" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13479" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89550" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13488" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1513">Задачи</a></li> <li><a href="/contest/1513/submit">Отослать</a></li> <li><a href="/contest/1513/my">Мои посылки</a></li> <li><a href="/contest/1513/status">Статус</a></li> <li><a href="/contest/1513/hacks">Взломы</a></li> <li><a href="/contest/1513/room/1">Комната</a></li> <li><a href="/contest/1513/standings">Положение</a></li> <li><a href="/contest/1513/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_40df154865f684144aed713fbf9108e03b5b4ef1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$ ($$$n \ge 2$$$) неотрицательных целых чисел $$$a_1, a_2, \dots, a_n$$$ называется хорошей, если для всех $$$i$$$ от $$$1$$$ до $$$n-1$$$ выполняется следующее условие: $$$$$$a_1 \: \&amp; \: a_2 \: \&amp; \: \dots \: \&amp; \: a_i = a_{i+1} \: \&amp; \: a_{i+2} \: \&amp; \: \dots \: \&amp; \: a_n,$$$$$$ где $$$\&amp;$$$ обозначает операцию <a href="https://bit.ly/2LBLVWv">побитового И</a>.</p><p>Вам дан массив $$$a$$$ размера $$$n$$$ ($$$n \geq 2$$$). Найдите количество перестановок $$$p$$$ чисел от $$$1$$$ до $$$n$$$, для которых последовательность $$$a_{p_1}$$$, $$$a_{p_2}$$$, ... ,$$$a_{p_n}$$$ является хорошей. Так как это число может быть большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — размер массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, где $$$i$$$-я строка содержит количество хороших перестановок в $$$i$$$-м наборе входных данных по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 1 1 5 1 2 3 4 5 5 0 2 0 3 0 4 1 3 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 0 36 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных все числа равны, поэтому все перестановки являются хорошими. Всего есть $$$6$$$ перестановок чисел от $$$1$$$ до $$$3$$$: $$$[1,2,3]$$$, $$$[1,3,2]$$$, $$$[2,1,3]$$$, $$$[2,3,1]$$$, $$$[3,1,2]$$$, $$$[3,2,1]$$$.</p><p>Во втором наборе входных данных можно показать, что хороших перестановок нет.</p><p>В третьем наборе входных данных существуют $$$36$$$ хороших перестановок. Например, перестановка $$$[1,5,4,2,3]$$$ дает последовательность $$$s=[0,0,3,2,0]$$$. Она хорошая, так как </p><ul> <li> $$$ s_1 = s_2 \: \&amp; \: s_3 \: \&amp; \: s_4 \: \&amp; \: s_5 = 0$$$, </li><li> $$$ s_1 \: \&amp; \: s_2 = s_3 \: \&amp; \: s_4 \: \&amp; \: s_5 = 0$$$, </li><li> $$$ s_1 \: \&amp; \: s_2 \: \&amp; \: s_3 = s_4 \: \&amp; \: s_5 = 0$$$, </li><li> $$$ s_1 \: \&amp; \: s_2 \: \&amp; \: s_3 \: \&amp; \: s_4 = s_5 = 0$$$. </li></ul><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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:53</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c18a89cd13ba',t:'MTY5NjY2NzE1My4xNTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\u043e\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", "\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", "*1400"]
1513C
1513
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>Вам дано целое число $$$n$$$. Вы должны сделать с ним $$$m$$$ операций.</p><p>В каждой операции вы <span class="tex-font-style-bf">должны</span> заменить все цифры числа $$$d$$$ десятичной записью числа $$$d + 1$$$. Например, число $$$1912$$$ становится числом $$$21023$$$ после одной операции.</p><p>Вам нужно найти длину числа $$$n$$$ после применения $$$m$$$ операций. Так как ответ может быть большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — количество наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит два целых числа $$$n$$$ ($$$1 \le n \le 10^9$$$) и $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — начальное число и количество операций. </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> 5 1912 1 5 6 999 1 88 2 12 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 2 6 4 2115 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$1912$$$ превращается в $$$21023$$$ после $$$1$$$ операции. Длина числа равна $$$5$$$.</p><p>Во втором наборе входных данных $$$5$$$ превращается в $$$21$$$ после $$$6$$$ операций. Длина числа равна $$$2$$$.</p><p>В третьем наборе входных данных $$$999$$$ превращается в $$$101010$$$ после $$$1$$$ операции. Длина числа равна $$$6$$$.</p><p>В четвертом наборе входных данных $$$88$$$ превращается в $$$1010$$$ после $$$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="a40cdbf41b063bb15077312d21bc1ed7"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cd03549350a7c14847d214f045ac3a7848c939ec"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a40cdbf41b063bb15077312d21bc1ed7'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1513%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='a40cdbf41b063bb15077312d21bc1ed7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1513">Divide by Zero 2021 and Codeforces Round 714 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a40cdbf41b063bb15077312d21bc1ed7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1513/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Произведение матриц, определитель, правило Крамера, системы линейных уравнений"> матрицы </span> </div> <div class="roundbox borderTopRound 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='a40cdbf41b063bb15077312d21bc1ed7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="954480"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a40cdbf41b063bb15077312d21bc1ed7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="954480"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89520" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13479" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89550" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13488" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1513">Задачи</a></li> <li><a href="/contest/1513/submit">Отослать</a></li> <li><a href="/contest/1513/my">Мои посылки</a></li> <li><a href="/contest/1513/status">Статус</a></li> <li><a href="/contest/1513/hacks">Взломы</a></li> <li><a href="/contest/1513/room/1">Комната</a></li> <li><a href="/contest/1513/standings">Положение</a></li> <li><a href="/contest/1513/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a3a7e9ea155a4ed690c06541c07b8f39578b6513"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Вам дано целое число $$$n$$$. Вы должны сделать с ним $$$m$$$ операций.</p><p>В каждой операции вы <span class="tex-font-style-bf">должны</span> заменить все цифры числа $$$d$$$ десятичной записью числа $$$d + 1$$$. Например, число $$$1912$$$ становится числом $$$21023$$$ после одной операции.</p><p>Вам нужно найти длину числа $$$n$$$ после применения $$$m$$$ операций. Так как ответ может быть большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — количество наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит два целых числа $$$n$$$ ($$$1 \le n \le 10^9$$$) и $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — начальное число и количество операций. </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> 5 1912 1 5 6 999 1 88 2 12 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 2 6 4 2115 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$1912$$$ превращается в $$$21023$$$ после $$$1$$$ операции. Длина числа равна $$$5$$$.</p><p>Во втором наборе входных данных $$$5$$$ превращается в $$$21$$$ после $$$6$$$ операций. Длина числа равна $$$2$$$.</p><p>В третьем наборе входных данных $$$999$$$ превращается в $$$101010$$$ после $$$1$$$ операции. Длина числа равна $$$6$$$.</p><p>В четвертом наборе входных данных $$$88$$$ превращается в $$$1010$$$ после $$$2$$$ операций. Длина числа равна $$$4$$$.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:54</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c192eea13380',t:'MTY5NjY2NzE1NC40OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "*1600"]
1513D
1513
D
ru
D. НОД и МОД
<div class="problem-statement"><div class="header"><div class="title">D. НОД и МОД</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ ($$$n \geq 2$$$) положительных целых чисел, а также целое число $$$p$$$. Рассмотрим неориентированный взвешенный граф на $$$n$$$ вершинах, пронумерованных от $$$1$$$ до $$$n$$$, в котором между вершинами $$$i$$$ и $$$j$$$ ($$$i&lt;j$$$) добавлены следующие ребра:</p><ul> <li> Если $$$gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$$$, то между вершинами $$$i$$$ и $$$j$$$ существует ребро веса $$$min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$$$. </li><li> Если $$$i+1=j$$$, то между вершинами $$$i$$$ и $$$j$$$ существует ребро веса $$$p$$$. </li></ul><p>Здесь $$$gcd(x, y, \ldots)$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольший общий делитель (НОД)</a> чисел $$$x$$$, $$$y$$$, ....</p><p>Обратите внимание, между вершинами $$$i$$$ и $$$j$$$ появляются кратные ребра, если оба условия выполнены. Если же ни одно условие не выполнено для $$$i$$$ и $$$j$$$, то между ними нет ребер.</p><p>Ваша цель — найти вес <a href="https://ru.wikipedia.org/wiki/Минимальное_остовное_дерево">минимального остовного дерева</a> данного графа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$p$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq p \leq 10^9$$$) — количество вершин и параметр $$$p$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Для каждого набора входных данных выведите вес соответствующего минимального остовного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 5 10 10 2 5 3 3 4 5 5 2 4 9 8 8 5 3 3 6 10 100 9 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 12 46 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже изображены графы для четырех наборов входных данных примера (ребра одного из минимальных остовных деревьев показаны розовым):</p><p><span class="tex-font-style-bf">Набор 1</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fbd5f4536bec34a1dbc98dc3679bdd574a132274.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-bf">Набор 2</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f11ee0a476af52f30318753c5e9b66a86aad12dc.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-bf">Набор 3</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/11ec1f337851b0eab129d6d349a04ca6223504f4.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-bf">Набор 4</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9c3e0e1143b65394c8cb776e7bc45b4e12d1b780.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="a255a11b426ba05418c4a57977830111"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cd03549350a7c14847d214f045ac3a7848c939ec"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='a255a11b426ba05418c4a57977830111'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1513%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='a255a11b426ba05418c4a57977830111'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1513">Divide by Zero 2021 and Codeforces Round 714 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='a255a11b426ba05418c4a57977830111'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1513/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств"> снм </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='a255a11b426ba05418c4a57977830111'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="954481"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a255a11b426ba05418c4a57977830111'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="954481"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89520" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13479" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89550" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13488" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1513">Задачи</a></li> <li><a href="/contest/1513/submit">Отослать</a></li> <li><a href="/contest/1513/my">Мои посылки</a></li> <li><a href="/contest/1513/status">Статус</a></li> <li><a href="/contest/1513/hacks">Взломы</a></li> <li><a href="/contest/1513/room/1">Комната</a></li> <li><a href="/contest/1513/standings">Положение</a></li> <li><a href="/contest/1513/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_80f1184e93a18b076189bf1caf69982492cb4ba1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. НОД и МОД</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ ($$$n \geq 2$$$) положительных целых чисел, а также целое число $$$p$$$. Рассмотрим неориентированный взвешенный граф на $$$n$$$ вершинах, пронумерованных от $$$1$$$ до $$$n$$$, в котором между вершинами $$$i$$$ и $$$j$$$ ($$$i&lt;j$$$) добавлены следующие ребра:</p><ul> <li> Если $$$gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$$$, то между вершинами $$$i$$$ и $$$j$$$ существует ребро веса $$$min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$$$. </li><li> Если $$$i+1=j$$$, то между вершинами $$$i$$$ и $$$j$$$ существует ребро веса $$$p$$$. </li></ul><p>Здесь $$$gcd(x, y, \ldots)$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольший общий делитель (НОД)</a> чисел $$$x$$$, $$$y$$$, ....</p><p>Обратите внимание, между вершинами $$$i$$$ и $$$j$$$ появляются кратные ребра, если оба условия выполнены. Если же ни одно условие не выполнено для $$$i$$$ и $$$j$$$, то между ними нет ребер.</p><p>Ваша цель — найти вес <a href="https://ru.wikipedia.org/wiki/Минимальное_остовное_дерево">минимального остовного дерева</a> данного графа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$p$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq p \leq 10^9$$$) — количество вершин и параметр $$$p$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Для каждого набора входных данных выведите вес соответствующего минимального остовного дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 5 10 10 2 5 3 3 4 5 5 2 4 9 8 8 5 3 3 6 10 100 9 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 12 46 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже изображены графы для четырех наборов входных данных примера (ребра одного из минимальных остовных деревьев показаны розовым):</p><p><span class="tex-font-style-bf">Набор 1</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fbd5f4536bec34a1dbc98dc3679bdd574a132274.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-bf">Набор 2</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f11ee0a476af52f30318753c5e9b66a86aad12dc.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-bf">Набор 3</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/11ec1f337851b0eab129d6d349a04ca6223504f4.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-bf">Набор 4</span></p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9c3e0e1143b65394c8cb776e7bc45b4e12d1b780.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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:55</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c19b494b7b53',t:'MTY5NjY2NzE1NS43OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\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", "\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\u043d\u043c", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2000"]
1513E
1513
E
ru
E. Ценовой баланс
<div class="problem-statement"><div class="header"><div class="title">E. Ценовой баланс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Массив называется красивым, если все его элементы равны.</p><p>Вы можете преобразовать некоторый массив, выполнив следующие шаги любое количество раз: </p><ol> <li> Выберите два индекса $$$i$$$ и $$$j$$$ ($$$1 \leq i,j \leq n$$$), а также целое число $$$x$$$ ($$$1 \leq x \leq a_i$$$). Назовем $$$i$$$ истоком, а $$$j$$$ — стоком. </li><li> Уменьшите $$$i$$$-й элемент на $$$x$$$, и увеличьте $$$j$$$-й элемент на $$$x$$$. Итоговые значения на $$$i$$$-й и $$$j$$$-й позициях равны $$$a_i-x$$$ и $$$a_j+x$$$ соответственно. </li><li> Стоимость такой операции равна $$$x \cdot |j-i| $$$. </li><li> После этой операции $$$i$$$ больше не может стать стоком, а $$$j$$$ больше не может стать истоком. </li></ol> Общая стоимость преобразования равна сумме стоимостей на шаге $$$3$$$.<p>Например, массив $$$[0, 2, 3, 3]$$$ может быть преобразован в красивый массив $$$[2, 2, 2, 2]$$$ с общей стоимостью $$$1 \cdot |1-3| + 1 \cdot |1-4| = 5$$$.</p><p>Массив называется сбалансированным, если его можно преобразовать в красивый массив, и стоимость такого преобразования <span class="tex-font-style-bf">однозначно</span> определена. Другими словами, минимальная стоимость преобразования в красивый массив равна максимальной стоимости.</p><p>Вам дан массив $$$a_1, a_2, \ldots, a_n$$$ длины $$$n$$$, элементы которого — неотрицательные целые числа. Ваша задача — найти количество сбалансированных массивов, являющихся перестановками данного. Два массива считаются различными, если элементы на некоторых позициях отличаются. Так как ответ может быть большим, выведите его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер массива. </p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — элементы массива.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество сбалансированных перестановок по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 4 0 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 11 12 13 14 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 120</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$[1, 2, 3]$$$ является сбалансированным массивом, так как мы можем выбрать индекс $$$3$$$ как исток, и индекс $$$1$$$ как сток. После этой операции мы получим красивый массив $$$[2, 2, 2]$$$, итоговая стоимость преобразования равна $$$2$$$. Можно показать, что это единственное возможная последовательность операций, приводящая к красивому массиву. Аналогично можно показать, что все другие перестановки тоже сбалансированные.</p><p>Во втором примере сбалансированные перестановки — это $$$[0, 0, 4, 4]$$$ и $$$[4, 4, 0, 0]$$$.</p><p>В третьем примере все перестановки являются сбалансированными.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2ec4053b5d22901444a5bc5c0e722935"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cd03549350a7c14847d214f045ac3a7848c939ec"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='2ec4053b5d22901444a5bc5c0e722935'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1513%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='2ec4053b5d22901444a5bc5c0e722935'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1513">Divide by Zero 2021 and Codeforces Round 714 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='2ec4053b5d22901444a5bc5c0e722935'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1513/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2300 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2ec4053b5d22901444a5bc5c0e722935'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="954482"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2ec4053b5d22901444a5bc5c0e722935'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="954482"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89520" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13479" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89550" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13488" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1513">Задачи</a></li> <li><a href="/contest/1513/submit">Отослать</a></li> <li><a href="/contest/1513/my">Мои посылки</a></li> <li><a href="/contest/1513/status">Статус</a></li> <li><a href="/contest/1513/hacks">Взломы</a></li> <li><a href="/contest/1513/room/1">Комната</a></li> <li><a href="/contest/1513/standings">Положение</a></li> <li><a href="/contest/1513/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_01793b05f90bb49950c4f637b4523dacf7720b81"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Ценовой баланс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Массив называется красивым, если все его элементы равны.</p><p>Вы можете преобразовать некоторый массив, выполнив следующие шаги любое количество раз: </p><ol> <li> Выберите два индекса $$$i$$$ и $$$j$$$ ($$$1 \leq i,j \leq n$$$), а также целое число $$$x$$$ ($$$1 \leq x \leq a_i$$$). Назовем $$$i$$$ истоком, а $$$j$$$ — стоком. </li><li> Уменьшите $$$i$$$-й элемент на $$$x$$$, и увеличьте $$$j$$$-й элемент на $$$x$$$. Итоговые значения на $$$i$$$-й и $$$j$$$-й позициях равны $$$a_i-x$$$ и $$$a_j+x$$$ соответственно. </li><li> Стоимость такой операции равна $$$x \cdot |j-i| $$$. </li><li> После этой операции $$$i$$$ больше не может стать стоком, а $$$j$$$ больше не может стать истоком. </li></ol> Общая стоимость преобразования равна сумме стоимостей на шаге $$$3$$$.<p>Например, массив $$$[0, 2, 3, 3]$$$ может быть преобразован в красивый массив $$$[2, 2, 2, 2]$$$ с общей стоимостью $$$1 \cdot |1-3| + 1 \cdot |1-4| = 5$$$.</p><p>Массив называется сбалансированным, если его можно преобразовать в красивый массив, и стоимость такого преобразования <span class="tex-font-style-bf">однозначно</span> определена. Другими словами, минимальная стоимость преобразования в красивый массив равна максимальной стоимости.</p><p>Вам дан массив $$$a_1, a_2, \ldots, a_n$$$ длины $$$n$$$, элементы которого — неотрицательные целые числа. Ваша задача — найти количество сбалансированных массивов, являющихся перестановками данного. Два массива считаются различными, если элементы на некоторых позициях отличаются. Так как ответ может быть большим, выведите его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер массива. </p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — элементы массива.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество сбалансированных перестановок по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 4 0 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 11 12 13 14 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 120</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$[1, 2, 3]$$$ является сбалансированным массивом, так как мы можем выбрать индекс $$$3$$$ как исток, и индекс $$$1$$$ как сток. После этой операции мы получим красивый массив $$$[2, 2, 2]$$$, итоговая стоимость преобразования равна $$$2$$$. Можно показать, что это единственное возможная последовательность операций, приводящая к красивому массиву. Аналогично можно показать, что все другие перестановки тоже сбалансированные.</p><p>Во втором примере сбалансированные перестановки — это $$$[0, 0, 4, 4]$$$ и $$$[4, 4, 0, 0]$$$.</p><p>В третьем примере все перестановки являются сбалансированными.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:57</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1a35ee15aa6',t:'MTY5NjY2NzE1Ny4yNDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\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", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2300"]
1513F
1513
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>Вам даны два массива $$$a$$$ и $$$b$$$, оба из $$$n$$$ элементов. Вы можете поменять местами два элемента в $$$b$$$ не более <span class="tex-font-style-bf">одного</span> раза (или ничего не делать). Вам нужно минимизировать величину $$$$$$\sum_{i}|a_{i}-b_{i}|.$$$$$$</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^9}$$$). </p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le {10^9}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимально возможное значение суммы $$$\sum_{i}|a_{i}-b_{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 5 4 3 2 1 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 3 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно поменять местами первый и пятый элементы массива $$$b$$$, и он станет равным $$$[ 5, 2, 3, 4, 1 ]$$$.</p><p>В таком случае значение суммы будет равно $$$|5-5| + |4-2| + |3-3| + |2-4| + |1-1| = 4$$$, что является минимумом.</p><p>Во втором примере можно поменять местами первый и второй элементы. Ответ равен $$$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="01d1ebbd43c4616b75a52c0b3071a553"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="cd03549350a7c14847d214f045ac3a7848c939ec"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='01d1ebbd43c4616b75a52c0b3071a553'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1513%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='01d1ebbd43c4616b75a52c0b3071a553'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1513">Divide by Zero 2021 and Codeforces Round 714 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='01d1ebbd43c4616b75a52c0b3071a553'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1513/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='01d1ebbd43c4616b75a52c0b3071a553'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="954483"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='01d1ebbd43c4616b75a52c0b3071a553'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="954483"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89520" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13479" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89550" title="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13488" resourceName="Divide by Zero 2021 and Codeforces Round #714 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1513">Задачи</a></li> <li><a href="/contest/1513/submit">Отослать</a></li> <li><a href="/contest/1513/my">Мои посылки</a></li> <li><a href="/contest/1513/status">Статус</a></li> <li><a href="/contest/1513/hacks">Взломы</a></li> <li><a href="/contest/1513/room/1">Комната</a></li> <li><a href="/contest/1513/standings">Положение</a></li> <li><a href="/contest/1513/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f94a44344f1be2b0198ba86952dfe759e7400741"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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>Вам даны два массива $$$a$$$ и $$$b$$$, оба из $$$n$$$ элементов. Вы можете поменять местами два элемента в $$$b$$$ не более <span class="tex-font-style-bf">одного</span> раза (или ничего не делать). Вам нужно минимизировать величину $$$$$$\sum_{i}|a_{i}-b_{i}|.$$$$$$</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^9}$$$). </p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le {10^9}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимально возможное значение суммы $$$\sum_{i}|a_{i}-b_{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 5 4 3 2 1 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4</pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 3 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно поменять местами первый и пятый элементы массива $$$b$$$, и он станет равным $$$[ 5, 2, 3, 4, 1 ]$$$.</p><p>В таком случае значение суммы будет равно $$$|5-5| + |4-2| + |3-3| + |2-4| + |1-1| = 4$$$, что является минимумом.</p><p>Во втором примере можно поменять местами первый и второй элементы. Ответ равен $$$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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:58</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1ac7cbd4991',t:'MTY5NjY2NzE1OC41NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\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", "*2500"]
1514A
1514
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$$$. Скажите, существует ли непустая подпоследовательность этого массива такая, что произведение ее элементов <span class="tex-font-style-bf">не</span> является полным квадратом.</p><p>Последовательность $$$b$$$ является подпоследовательностью массива $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно, ни одного) элементов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — длину массива $$$a$$$.</p><p>Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если существует подпоследовательность массива $$$a$$$, произведение элементов которой не является полным квадратом, выведите «<span class="tex-font-style-tt">YES</span>». Иначе, выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 5 4 2 100 10000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, произведение элементов всего массива ($$$20$$$) не является полным квадратом.</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="efdeabf62c02de53069afd8c3ad276e0"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4211f79dc47902feac4c5a814eddba645950df56"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='efdeabf62c02de53069afd8c3ad276e0'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1514%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='efdeabf62c02de53069afd8c3ad276e0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1514">Codeforces Round 716 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='efdeabf62c02de53069afd8c3ad276e0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1514/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='efdeabf62c02de53069afd8c3ad276e0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="962258"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='efdeabf62c02de53069afd8c3ad276e0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="962258"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89771" title="Codeforces Round #716 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13531" resourceName="Codeforces Round #716 (Div.2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89810" title="Codeforces round #716 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13539" resourceName="Codeforces round #716 editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1514">Задачи</a></li> <li><a href="/contest/1514/submit">Отослать</a></li> <li><a href="/contest/1514/my">Мои посылки</a></li> <li><a href="/contest/1514/status">Статус</a></li> <li><a href="/contest/1514/hacks">Взломы</a></li> <li><a href="/contest/1514/room/1">Комната</a></li> <li><a href="/contest/1514/standings">Положение</a></li> <li><a href="/contest/1514/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d3d64092480ede5d1a7c7c405f580335253dce94"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</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$$$. Скажите, существует ли непустая подпоследовательность этого массива такая, что произведение ее элементов <span class="tex-font-style-bf">не</span> является полным квадратом.</p><p>Последовательность $$$b$$$ является подпоследовательностью массива $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно, ни одного) элементов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — длину массива $$$a$$$.</p><p>Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если существует подпоследовательность массива $$$a$$$, произведение элементов которой не является полным квадратом, выведите «<span class="tex-font-style-tt">YES</span>». Иначе, выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 5 4 2 100 10000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, произведение элементов всего массива ($$$20$$$) не является полным квадратом.</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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:25:59</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1b4cc089d76',t:'MTY5NjY2NzE2MC4wMTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*800"]
1514B
1514
B
ru
B. AND 0, большая сумма
<div class="problem-statement"><div class="header"><div class="title">B. AND 0, большая сумма</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>Первыми словами маленького Бадави были «AND 0 большая сумма», поэтому он решил решить следующую задачу. Даны два целых числа $$$n$$$ и $$$k$$$, вычислите количество массивов длины $$$n$$$, таких что: </p><ul> <li> все элементы массива это целые числа от $$$0$$$ до $$$2^k-1$$$ (включительно); </li><li> <a href="https://bit.ly/2LBLVWv">побитовое И</a> всех его элементов это $$$0$$$; </li><li> сумма его элементов максимальная возможная. </li></ul><p>Так как ответ может быть очень большим, выведите его остаток от деления на $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора входных данных даны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 20$$$).</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> 2 2 2 100000 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 226732710 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подходят $$$4$$$ массива:</p><ul> <li> $$$[3,0]$$$, </li><li> $$$[0,3]$$$, </li><li> $$$[1,2]$$$, </li><li> $$$[2,1]$$$. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f902270b696760117e8fa77331cb6a67"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4211f79dc47902feac4c5a814eddba645950df56"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='f902270b696760117e8fa77331cb6a67'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1514%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='f902270b696760117e8fa77331cb6a67'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1514">Codeforces Round 716 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='f902270b696760117e8fa77331cb6a67'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1514/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound 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='f902270b696760117e8fa77331cb6a67'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="962259"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f902270b696760117e8fa77331cb6a67'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="962259"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89771" title="Codeforces Round #716 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13531" resourceName="Codeforces Round #716 (Div.2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89810" title="Codeforces round #716 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13539" resourceName="Codeforces round #716 editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1514">Задачи</a></li> <li><a href="/contest/1514/submit">Отослать</a></li> <li><a href="/contest/1514/my">Мои посылки</a></li> <li><a href="/contest/1514/status">Статус</a></li> <li><a href="/contest/1514/hacks">Взломы</a></li> <li><a href="/contest/1514/room/1">Комната</a></li> <li><a href="/contest/1514/standings">Положение</a></li> <li><a href="/contest/1514/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c82c18c077a628faa4f8a9c1afe05b4764dd1a3a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. AND 0, большая сумма</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>Первыми словами маленького Бадави были «AND 0 большая сумма», поэтому он решил решить следующую задачу. Даны два целых числа $$$n$$$ и $$$k$$$, вычислите количество массивов длины $$$n$$$, таких что: </p><ul> <li> все элементы массива это целые числа от $$$0$$$ до $$$2^k-1$$$ (включительно); </li><li> <a href="https://bit.ly/2LBLVWv">побитовое И</a> всех его элементов это $$$0$$$; </li><li> сумма его элементов максимальная возможная. </li></ul><p>Так как ответ может быть очень большим, выведите его остаток от деления на $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора входных данных даны два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 20$$$).</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> 2 2 2 100000 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 226732710 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подходят $$$4$$$ массива:</p><ul> <li> $$$[3,0]$$$, </li><li> $$$[0,3]$$$, </li><li> $$$[1,2]$$$, </li><li> $$$[2,1]$$$. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:26:01</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1bdba5475b7',t:'MTY5NjY2NzE2MS4zMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1200"]
1514C
1514
C
ru
C. Произведение 1 по модулю N
<div class="problem-statement"><div class="header"><div class="title">C. Произведение 1 по модулю N</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>А вот первые слова маленького Эхаба: «Дано целое число $$$n$$$, найдите самую длинную подпоследовательность массива $$$[1,2, \ldots, n-1]$$$, произведение элементов которой равно $$$1$$$ по модулю $$$n$$$». Решите эту задачу.</p><p>Последовательность $$$b$$$ является подпоследовательностью массива $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно, всех) элементов. Произведение элементов пустой подпоследовательности равно $$$1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке дано целое число $$$n$$$ ($$$2 \le n \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите длину найденной подпоследовательности.</p><p>Во второй строке выведите элементы подпоследовательности <span class="tex-font-style-bf">в возрастающем порядке</span>.</p><p>Если существует несколько ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 3 5 7 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере произведение элементов равно $$$6$$$, что равно $$$1$$$ по модулю $$$5$$$. Единственная более длинная последовательность это $$$[1,2,3,4]$$$. Произведение ее элементов равно $$$24$$$, что равно $$$4$$$ по модулю $$$5$$$. Поэтому, ответ это $$$[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="0f5341ccacd81dcafaa05cb18c008c6a"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4211f79dc47902feac4c5a814eddba645950df56"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0f5341ccacd81dcafaa05cb18c008c6a'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1514%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='0f5341ccacd81dcafaa05cb18c008c6a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1514">Codeforces Round 716 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='0f5341ccacd81dcafaa05cb18c008c6a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1514/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound 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='0f5341ccacd81dcafaa05cb18c008c6a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="962260"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0f5341ccacd81dcafaa05cb18c008c6a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="962260"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89771" title="Codeforces Round #716 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13531" resourceName="Codeforces Round #716 (Div.2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89810" title="Codeforces round #716 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13539" resourceName="Codeforces round #716 editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1514">Задачи</a></li> <li><a href="/contest/1514/submit">Отослать</a></li> <li><a href="/contest/1514/my">Мои посылки</a></li> <li><a href="/contest/1514/status">Статус</a></li> <li><a href="/contest/1514/hacks">Взломы</a></li> <li><a href="/contest/1514/room/1">Комната</a></li> <li><a href="/contest/1514/standings">Положение</a></li> <li><a href="/contest/1514/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c72ee14c758a01d71ffccdd68ed48da4321219be"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Произведение 1 по модулю N</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>А вот первые слова маленького Эхаба: «Дано целое число $$$n$$$, найдите самую длинную подпоследовательность массива $$$[1,2, \ldots, n-1]$$$, произведение элементов которой равно $$$1$$$ по модулю $$$n$$$». Решите эту задачу.</p><p>Последовательность $$$b$$$ является подпоследовательностью массива $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно, всех) элементов. Произведение элементов пустой подпоследовательности равно $$$1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке дано целое число $$$n$$$ ($$$2 \le n \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите длину найденной подпоследовательности.</p><p>Во второй строке выведите элементы подпоследовательности <span class="tex-font-style-bf">в возрастающем порядке</span>.</p><p>Если существует несколько ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 3 5 7 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере произведение элементов равно $$$6$$$, что равно $$$1$$$ по модулю $$$5$$$. Единственная более длинная последовательность это $$$[1,2,3,4]$$$. Произведение ее элементов равно $$$24$$$, что равно $$$4$$$ по модулю $$$5$$$. Поэтому, ответ это $$$[1,2,3]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:26:02</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1c5fa8d9d3d',t:'MTY5NjY2NzE2Mi43MTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
1514D
1514
D
ru
D. Вырежи и склей
<div class="problem-statement"><div class="header"><div class="title">D. Вырежи и склей</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У маленького Эхаба есть набор для аппликации, содержащий массив $$$a$$$ длины $$$n$$$. Он планирует взять ножницы и сделать следующее:</p><ul> <li> выбрать отрезок $$$(l, r)$$$, и вырезать каждый элемент $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ на этом отрезке; </li><li> склеить некоторые из элементов вместе в том же порядке, в котором они шли в массиве; </li><li> в итоге, получится несколько кусочков, каждый кусочек содержит некоторые элементы, и каждый элемент принадлежит какому-то кусочку. </li></ul><p>Более формально, он разделит последовательность $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ на подпоследовательности. Он считает, что разделение красивое, если для каждого кусочка (подпоследовательности) верно, что если его длина равна $$$x$$$, то никакое значение не встречается строго больше $$$\lceil \frac{x}{2} \rceil$$$ раз в этом кусочке.</p><p>Эхаб еще не определился с отрезком, поэтому он интересуется для $$$q$$$ отрезков $$$(l, r)$$$, чему равно минимальное количество кусочков, на которые нужно разделить $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$, чтобы разделение было красивым.</p><p>Последовательность $$$b$$$ является подпоследовательностью массива $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно, ни одного) элементов. Обратите внимание, что она не обязательно должна быть непрерывной.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — длина массива $$$a$$$ и количество запросов.</p><p>Во второй строке даны $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — элементы массива $$$a$$$.</p><p>Каждая из следующих $$$q$$$ строк содержит два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \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> 6 2 1 3 2 3 3 2 1 6 2 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>В первом запросе можно взять весь массив в одну подпоследовательность, так как его длина равна $$$6$$$, и ни одно значение не встречается в нем больше $$$3$$$ раз.</p><p>Во втором запросе элементы отрезка равны $$$[3,2,3,3]$$$. Вы не можете взять их всех в одну подпоследовательность, потому что ее длина будет равна $$$4$$$, и $$$3$$$ встречается в ней больше $$$2$$$ раз. Однако, вы можете разделить отрезок на две подпоследовательности: $$$[3]$$$ и $$$[2,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="e18021597998796434d09d6c9358c54d"/> <meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery-1.8.3.js"></script> <script type="application/javascript"> window.locale = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1); } </script> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="expires" content="-1"> <meta http-equiv="profileName" content="j1"> <meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/> <meta property="fb:admins" content="100001352546622" /> <meta property="og:image" content="//codeforces.org/s/86568/images/codeforces-sponsored-by-ton.png" /> <link rel="image_src" href="//codeforces.org/s/86568/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="4211f79dc47902feac4c5a814eddba645950df56"/> <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/86568/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/86568/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/86568/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/86568/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/86568/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/86568/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/86568/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/86568/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/86568/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/86568/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/86568/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/86568/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/86568/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/86568/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/86568/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/community.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/86568/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/8070da8e33c491bfcabae41949552d62/ru/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/preparedVerdictFormats-ru.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/86568/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/86568/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> <script type="text/javascript" src="//codeforces.org/s/86568/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='e18021597998796434d09d6c9358c54d'>&nbsp;</span> <!-- .notificationTextCleaner used in Codeforces.showAnnouncements() --> <div class="notificationTextCleaner" style="font-size: 0"></div> <div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div> <div class="verdictPrototypeDiv" style="display: none;"></div> <!-- Codeforces JavaScripts. --> <script type="text/javascript"> String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var queryMobile = Codeforces.queryString.mobile; if (queryMobile === "true" || queryMobile === "false") { Codeforces.putToStorage("useMobile", queryMobile === "true"); } else { var useMobile = Codeforces.getFromStorage("useMobile"); if (useMobile === true || useMobile === false) { if (useMobile != false) { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile)); } } } </script> <script type="text/javascript"> if (window.parent.frames.length > 0) { window.stop(); } </script> <script type="text/javascript"> $(document).ready(function () { (function () { jQuery.expr[':'].containsCI = function(elem, index, match) { return !match || !match.length || match.length < 4 || !match[3] || ( elem.textContent || elem.innerText || jQuery(elem).text() || '' ).toLowerCase().indexOf(match[3].toLowerCase()) >= 0; } }(jQuery)); $.ajaxPrefilter(function(options, originalOptions, xhr) { var csrf = Codeforces.getCsrfToken(); if (csrf) { var data = originalOptions.data; if (originalOptions.data !== undefined) { if (Object.prototype.toString.call(originalOptions.data) === '[object String]') { data = $.deparam(originalOptions.data); } } else { data = {}; } options.data = $.param($.extend(data, { csrf_token: csrf })); } }); window.getCodeforcesServerTime = function(callback) { $.post("/data/time", {}, callback, "json"); } window.updateTypography = function () { $("div.ttypography code").addClass("tt"); $("div.ttypography pre>code").addClass("prettyprint").removeClass("tt"); $("div.ttypography table").addClass("bordertable"); prettyPrint(); } $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: { 'X-Csrf-Token': Codeforces.getCsrfToken() }}); window.updateTypography(); Codeforces.signForms(); setTimeout(function() { $(".second-level-menu-list").lavaLamp({ fx: "backout", speed: 700 }); }, 100); Codeforces.countdown(); $("a[rel='photobox']").colorbox(); function showAnnouncements(json) { //info("j=" + JSON.stringify(json)); if (json.t != "a") { return; } setTimeout(function() { Codeforces.showAnnouncements(json.d, "ru"); }, Math.random() * 500); } function showEventCatcherUserMessage(json) { if (json.t == "s") { var points = json.d[5]; var passedTestCount = json.d[7]; var judgedTestCount = json.d[8]; var verdict = preparedVerdictFormats[json.d[12]]; var verdictPrototypeDiv = $(".verdictPrototypeDiv"); verdictPrototypeDiv.html(verdict); if (judgedTestCount != null && judgedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount); } if (passedTestCount != null && passedTestCount != undefined) { verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount); } if (points != null && points != undefined) { verdictPrototypeDiv.find(".verdict-format-points").text(points); } Codeforces.showMessage(verdictPrototypeDiv.text()); } } $(".clickable-title").each(function() { var title = $(this).attr("data-title"); if (title) { var tmp = document.createElement("DIV"); tmp.innerHTML = title; $(this).attr("title", tmp.textContent || tmp.innerText || ""); } }); $(".clickable-title").click(function() { var title = $(this).attr("data-title"); if (title) { Codeforces.alert(title); } else { Codeforces.alert($(this).attr("title")); } }).css("position", "relative").css("bottom", "3px"); Codeforces.showDelayedMessage(); Codeforces.reformatTimes(); //Codeforces.initializePubSub(); if (window.codeforcesOptions.subscribeServerUrl) { window.eventCatcher = new EventCatcher( window.codeforcesOptions.subscribeServerUrl, [ Codeforces.getGlobalChannel(), Codeforces.getUserChannel(), Codeforces.getUserShowMessageChannel(), Codeforces.getContestChannel(), Codeforces.getParticipantChannel(), Codeforces.getTalkChannel() ] ); if (Codeforces.getParticipantChannel()) { window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getContestChannel()) { window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getGlobalChannel()) { window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserChannel()) { window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) { showAnnouncements(json); }); } if (Codeforces.getUserShowMessageChannel()) { window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) { showEventCatcherUserMessage(json); }); } } Codeforces.setupContestTimes("/data/contests"); Codeforces.setupSpoilers(); Codeforces.setupTutorials("/data/problemTutorial"); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-743380-5']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <div id="body"> <div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;"> <span class="icon-stack" style="width: 100%;"> <i class="icon-circle icon-stack-base"></i> <i class="icon-bell-alt icon-light"></i> </span> <br/> <span 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/86568/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/86568/images/flags/24/gb.png" title="In English" alt="In English"/></a> <a href="?locale=ru"><img src="//codeforces.org/s/86568/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a> </div> <div > <a href="/enter?back=%2Fcontest%2F1514%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='e18021597998796434d09d6c9358c54d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1514">Codeforces Round 716 (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">&rarr; Дорешивание? <div class="top-links"> </div> </div> <div> <div style="margin:1em;font-size:0.8em;"> Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание. </div> <div style="text-align:center;margin:1em;"> <form action="" method="post"><input type='hidden' name='csrf_token' value='e18021597998796434d09d6c9358c54d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;"> </form> </div> </div> </div> <div class="roundbox sidebox ContestVirtualFrame borderTopRound " style=""> <div class="caption titled">&rarr; Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i> <div class="top-links"> </div> </div> <div style=" " data-page-url="/data/sidebarFrames" > <div style="margin:1em;font-size:0.8em;"> Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований. Если вы раньше видели эти задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве. Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо. </div> <div style="text-align:center;margin:1em;"> <form action="/contest/1514/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='e18021597998796434d09d6c9358c54d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="962261"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e18021597998796434d09d6c9358c54d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="962261"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace; } </style> <div class="roundbox sidebox sidebar-menu borderTopRound " style=""> <div class="caption titled">&rarr; Материалы соревнования <div class="top-links"> </div> </div> <ul> <li> <span> <a href="/blog/entry/89771" title="Codeforces Round #716 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13531" resourceName="Codeforces Round #716 (Div.2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/89810" title="Codeforces round #716 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13539" resourceName="Codeforces round #716 editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1514">Задачи</a></li> <li><a href="/contest/1514/submit">Отослать</a></li> <li><a href="/contest/1514/my">Мои посылки</a></li> <li><a href="/contest/1514/status">Статус</a></li> <li><a href="/contest/1514/hacks">Взломы</a></li> <li><a href="/contest/1514/room/1">Комната</a></li> <li><a href="/contest/1514/standings">Положение</a></li> <li><a href="/contest/1514/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6f31209edcc3d7f69a0bb5587c54d5313d625f83"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Вырежи и склей</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У маленького Эхаба есть набор для аппликации, содержащий массив $$$a$$$ длины $$$n$$$. Он планирует взять ножницы и сделать следующее:</p><ul> <li> выбрать отрезок $$$(l, r)$$$, и вырезать каждый элемент $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ на этом отрезке; </li><li> склеить некоторые из элементов вместе в том же порядке, в котором они шли в массиве; </li><li> в итоге, получится несколько кусочков, каждый кусочек содержит некоторые элементы, и каждый элемент принадлежит какому-то кусочку. </li></ul><p>Более формально, он разделит последовательность $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$ на подпоследовательности. Он считает, что разделение красивое, если для каждого кусочка (подпоследовательности) верно, что если его длина равна $$$x$$$, то никакое значение не встречается строго больше $$$\lceil \frac{x}{2} \rceil$$$ раз в этом кусочке.</p><p>Эхаб еще не определился с отрезком, поэтому он интересуется для $$$q$$$ отрезков $$$(l, r)$$$, чему равно минимальное количество кусочков, на которые нужно разделить $$$a_l$$$, $$$a_{l + 1}$$$, ..., $$$a_r$$$, чтобы разделение было красивым.</p><p>Последовательность $$$b$$$ является подпоследовательностью массива $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно, ни одного) элементов. Обратите внимание, что она не обязательно должна быть непрерывной.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n,q \le 3 \cdot 10^5$$$) — длина массива $$$a$$$ и количество запросов.</p><p>Во второй строке даны $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{n}$$$ ($$$1 \le a_i \le n$$$) — элементы массива $$$a$$$.</p><p>Каждая из следующих $$$q$$$ строк содержит два целых числа $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \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> 6 2 1 3 2 3 3 2 1 6 2 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>В первом запросе можно взять весь массив в одну подпоследовательность, так как его длина равна $$$6$$$, и ни одно значение не встречается в нем больше $$$3$$$ раз.</p><p>Во втором запросе элементы отрезка равны $$$[3,2,3,3]$$$. Вы не можете взять их всех в одну подпоследовательность, потому что ее длина будет равна $$$4$$$, и $$$3$$$ встречается в ней больше $$$2$$$ раз. Однако, вы можете разделить отрезок на две подпоследовательности: $$$[3]$$$ и $$$[2,3,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/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:26:04</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c1ce9fc715f6',t:'MTY5NjY2NzE2NC4wOTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2000"]